Follow links to add evaluation to evaluate
T = 0.2
Prompt Override = insert
| Test | Run 0 | Run 1 | Run 2 | Run 3 | Run 4 |
|---|---|---|---|---|---|
| aa_polarity | Fail | Fail | Fail | Pass | Fail |
| adiabatic_expansion | Pass | Pass | Pass | Pass | Pass |
| alignment | Pass | Pass | Pass | Pass | Pass |
| angle | Pass | Pass | Pass | Pass | Pass |
| aromatic_aa | Pass | Pass | Pass | Pass | Pass |
| arrhenius | Pass | Pass | Fail | Pass | Pass |
| bimolecular | Pass | Pass | Pass | Pass | Pass |
| bb_rad | Pass | Pass | Pass | Pass | Pass |
| blast | Fail | Fail | Fail | Fail | Fail |
| bravais | Pass | Pass | Pass | Pass | Pass |
| canonicalize | Pass | Pass | Pass | Pass | Pass |
| carnot_efficiency | Pass | Pass | Pass | Pass | Pass |
| claussius | Pass | Fail | Pass | Pass | Pass |
| compare_electronegativity | Fail | Fail | Fail | Fail | Fail |
| condiff_1d | Pass | Pass | Pass | Pass | Pass |
| cubes | Pass | Pass | Pass | Fail | Pass |
| de_broglie | Pass | Pass | Pass | Pass | Pass |
| derivative1d-ch | Pass | Pass | Pass | Pass | Pass |
| derivative_2deg | Pass | Pass | Pass | Pass | Pass |
| descriptors | Fail | Fail | Pass | Pass | Fail |
| dipole | Pass | Pass | Pass | Pass | Pass |
| dou | Fail | Fail | Fail | Fail | Fail |
| eigen-ch | Pass | Pass | Pass | Pass | Pass |
| eigen | Pass | Pass | Pass | Pass | Pass |
| element_mass | Pass | Fail | Fail | Fail | Pass |
| element_name | Pass | Pass | Pass | Pass | Pass |
| energy_of_e | Pass | Pass | Pass | Pass | Pass |
| find_indices | Fail | Fail | Fail | Fail | Fail |
| force_constant | Fail | Fail | Fail | Fail | Fail |
| fourier_1d | Pass | Pass | Pass | Pass | Pass |
| freezing_depression | Pass | Pass | Pass | Pass | Pass |
| genpos | Fail | Fail | Fail | Fail | Fail |
| heating_water | Fail | Fail | Fail | Fail | Fail |
| hydrophobic_res | Fail | Pass | Fail | Fail | Fail |
| ideal_gas | Pass | Pass | Pass | Pass | Pass |
| integral | Fail | Fail | Fail | Fail | Fail |
| trap | Pass | Pass | Pass | Pass | Pass |
| invert_matrix | Pass | Pass | Pass | Pass | Pass |
| iupac2smiles | Fail | Fail | Fail | Fail | Fail |
| kld | Pass | Pass | Pass | Pass | Pass |
| langevin_dynamics | Fail | Fail | Fail | Fail | Fail |
| weighted-least-squares | Fail | Fail | Pass | Fail | Fail |
| lipinski_rule_of_five | Pass | Pass | Pass | Pass | Pass |
| mape | Fail | Fail | Fail | Fail | Fail |
| mapping_operator | Fail | Fail | Fail | Fail | Fail |
| matpow | Pass | Pass | Pass | Pass | Pass |
| matrix_factorial | Pass | Pass | Pass | Pass | Pass |
| max-boltz | Pass | Pass | Pass | Pass | Pass |
| michaelis | Pass | Pass | Pass | Pass | Pass |
| mol_charge | Fail | Pass | Fail | Pass | Fail |
| net_charge | Pass | Pass | Pass | Pass | Pass |
| solve_ode | Fail | Fail | Fail | Fail | Fail |
| ohe | Pass | Fail | Fail | Fail | Fail |
| osmotic_pressure | Pass | Pass | Pass | Fail | Pass |
| pair_wise | Fail | Fail | Fail | Fail | Fail |
| pi | Pass | Pass | Pass | Pass | Pass |
| pib_1d | Pass | Pass | Pass | Pass | Pass |
| pred_interval | Fail | Pass | Pass | Pass | Pass |
| pubchem | Fail | Fail | Fail | Fail | Fail |
| pyscf_energy | Fail | Fail | Fail | Fail | Fail |
| qed | Fail | Fail | Fail | Fail | Fail |
| quantile | Fail | Pass | Fail | Fail | Fail |
| random_walk | Fail | Pass | Pass | Fail | Fail |
| rank | Pass | Pass | Pass | Pass | Pass |
| remove-water | Pass | Pass | Pass | Pass | Pass |
| rms_velocity | Fail | Fail | Fail | Pass | Pass |
| rmse | Pass | Pass | Pass | Pass | Pass |
| rog | Pass | Pass | Pass | Pass | Pass |
| sasa | Fail | Pass | Fail | Pass | Pass |
| scaffold | Fail | Fail | Fail | Fail | Fail |
| seq-align | Fail | Fail | Fail | Fail | Fail |
| seq-trans | Pass | Pass | Fail | Pass | Pass |
| sequence | Pass | Pass | Pass | Pass | Fail |
| sle | Fail | Fail | Fail | Fail | Fail |
| spectral_r | Pass | Pass | Pass | Pass | Pass |
| find_peaks | Fail | Fail | Fail | Fail | Fail |
| speed_of_sound | Fail | Fail | Fail | Fail | Fail |
| substructure | Fail | Fail | Fail | Fail | Fail |
| tanimoto | Pass | Pass | Pass | Pass | Pass |
| unbdistance | Fail | Fail | Fail | Fail | Fail |
aa_polarity
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
[insert]
return countimport math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in range(len(sequence)):
if sequence[i] == "R" or sequence[i] == "K" or sequence[i] == "D" or sequence[i] == "E":
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == 'S' or i == 'T' or i == 'N' or i == 'Q' or i == 'H' or i == 'K' or i == 'R':
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == 'R' or i == 'K' or i == 'D' or i == 'E' or i == 'Q' or i == 'N' or i == 'H' or i == 'S' or i == 'T' or i == 'Y' or i == 'C' or i == 'M' or i == 'W':
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i in "STNQ":
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == "S" or i == "T" or i == "N" or i == "Q" or i == "H" or i == "K" or i == "R":
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
adiabatic_expansion
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
[insert]
return T2
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2=T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
alignment
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
[insert]
return trajimport mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
angle
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
[insert]
return angleimport numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
aromatic_aa
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
[insert]
return countimport math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for i in sequence:
if i == 'F' or i == 'Y' or i == 'W':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for aa in sequence:
if aa == "F" or aa == "Y" or aa == "W":
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for i in sequence:
if i == "F" or i == "Y" or i == "W":
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for aa in sequence:
if aa == 'F' or aa == 'Y' or aa == 'W':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for i in sequence:
if i == "F" or i == "Y" or i == "W":
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
arrhenius
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
[insert]
return k1import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((-Ea/8.314)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2 * math.exp((Ea/8.314)*((1/T2)-(1/T1)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((Ea/8.314)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1=k2*math.exp((-Ea/8.314)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((Ea/8.314)*(1/T2-1/T1))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
bimolecular
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
[insert]
return rateimport math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
bb_rad
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
[insert]
return Bimport numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3e8
k = 1.38e-23
B = 2*h*c**2/lam**5 * 1/(np.exp(h*c/(lam*k*T))-1)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
B = 2.0*h*c**2/(lam**5*(np.exp(h*c/(lam*k*T))-1.0))
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
B = 2.0*h*c**2/lam**5*1.0/(np.exp(h*c/(lam*k*T))-1.0)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3e8
k = 1.38e-23
B = 2*h*c**2/lam**5*1/(np.exp(h*c/(lam*k*T))-1)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.62607004e-34
c = 299792458
k = 1.38064852e-23
B = 2*h*c**2/(lam**5*(np.exp(h*c/(lam*k*T))-1))
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
blast
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
[insert]
return e, idimport requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
from Bio.Blast import NCBIWWW
from Bio import SeqIO
from Bio.Blast import NCBIXML
from Bio import AlignIO
from Bio.Align.Applications import ClustalwCommandline
from Bio import Phylo
import os
import subprocess
import re
import numpy as np
# 2. Submit BLAST search with sequences
result_handle = NCBIWWW.qblast("blastn", "nt", seq)
# 3. Get result
blast_records = NCBIXML.parse(result_handle)
# 4. Parse MSA
blast_record = next(blast_records)
alignment = blast_record.alignments[0]
hsp = alignment.hsps[0]
e = hsp.expect
id = alignment.title
# 5. Return a tuple of e score, id of top match
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
Error message from NCBI: Message ID#24 Error: Failed to read the Blast query: Protein FASTA provided for nucleotide sequence
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'QUERY': seq, 'PROGRAM': 'blastp', 'DATABASE': 'nr',
'FILTER': 'L', 'EXPECT': '10', 'HITLIST_SIZE': '1',
'CMD': 'Put'}
r = requests.post(url, data=params)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
result = soup.find('pre')
# 4. Parse MSA
msa = result.text.split('Query=')[1].split('\n\n')[1].split('\n')[1:]
msa = [x.split()[1] for x in msa]
msa = np.array([list(x) for x in msa])
# 5. Return a tuple of e score, id of top match
e = result.text.split('Expect = ')[1].split('\n')[0]
id = result.text.split('>')[1].split('\n')[0]
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
'NoneType' object has no attribute 'text'
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1.
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2.
r = requests.post(
"https://blast.ncbi.nlm.nih.gov/Blast.cgi",
data={
"QUERY": seq,
"PROGRAM": "blastp",
"DATABASE": "nr",
"CMD": "Put",
"HITLIST_SIZE": 1,
"FILTER": "L",
"EXPECT": 10,
"FORMAT_TYPE": "HTML",
"CLIENT": "web",
"SERVICE": "plain",
"PAGE": "Nucleotides",
"NCBI_GI": "on",
"CMD": "Put",
"RID": "",
"FORMAT_OBJECT": "Alignment",
"FORMAT_TYPE": "HTML",
"DESCRIPTIONS": 500,
"ALIGNMENTS": 500,
"NCBI_GI": "on",
"SHOW_OVERVIEW": "on",
"SHOW_LINKOUT": "on",
"GET_SEQUENCE": "on",
"CDD_SEARCH": "on",
"BLAST_PROGRAMS": "blastp",
"PAGE": "Nucleotides",
"PROGRAM": "blastp",
"CLIENT": "web",
"SERVICE": "plain",
"CMD": "Get",
"RID": "",
"FORMAT_TYPE": "HTML",
"RID": "",
"FORMAT_TYPE": "HTML",
"DESCRIPTIONS": 500,
"ALIGNMENTS": 500,
"NCBI_GI": "on",
"SHOW_OVERVIEW": "on",
"SHOW_LINKOUT": "on",
"GET_SEQUENCE": "on",
"CDD_SEARCH": "on",
"BLAST_PROGRAMS": "blastp",
"PAGE": "Nucleotides",
"PROGRAM": "blastp",
"CLIENT": "web",
"SERVICE": "plain",
"CMD": "Get",
"RID": "",
"FORMAT_TYPE": "HTML",
"RID": "",
"FORMAT_TYPE": "HTML",
"DESCRIPTIONS": 500,
"ALIGNMENTS": 500,
"NCBI_GI": "on",
"SHOW_OVERVIEW": "on",
"SHOW_LINKOUT": "on",
"GET_SEQUENCE": "on",
"CDD_SEARCH": "on",
"BLAST_PROGRAMS": "blastp",
"PAGE": "Nucleotides",
"PROGRAM": "blastp",
"CLIENT": "web",
"SERVICE": "plain",
"CMD": "Get",
"RID": "",
"FORMAT_TYPE": "HTML",
"RID": "",
"FORMAT_TYPE": "HTML",
"DESCRIPTIONS": 500,
"ALIGNMENTS": 500,
"NCBI_GI": "on",
"SHOW_OVERVIEW": "on",
"SHOW_LINKOUT": "on",
"GET_SEQUENCE": "on",
"CDD_SEARCH": "on",
"BLAST_PROGRAMS": "blastp",
"PAGE": "Nucleotides",
"PROGRAM": "blastp",
"CLIENT": "web",
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
invalid syntax (<string>, line 104)
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1.
import requests
from bs4 import BeautifulSoup
# 2.
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'PAGE': 'Nucleotides',
'PROGRAM': 'blastn',
'DATABASE': 'nr',
'QUERY': seq}
r = requests.post(url, data=params)
# 3.
soup = BeautifulSoup(r.text, 'html.parser')
msa = soup.find_all('pre')[1].text
# 4.
msa = msa.split('\n')
msa = [i.split(' ') for i in msa]
msa = [i for i in msa if len(i) > 1]
msa = np.array(msa)
# 5.
e = msa[0, -1]
id = msa[0, 1]
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1.
from bs4 import BeautifulSoup
import requests
import numpy as np
# 2.
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'QUERY': seq, 'PROGRAM': 'blastp', 'DATABASE': 'nr', 'CMD': 'Put'}
r = requests.get(url, params=params)
# 3.
r = requests.get(r.url, stream=True)
soup = BeautifulSoup(r.text, 'html.parser')
msa = soup.find('pre').text
# 4.
msa = msa.split('\n')
msa = [x for x in msa if x != '']
msa = [x for x in msa if x[0] != '>']
msa = [x for x in msa if x[0] != ' ']
msa = [x for x in msa if x[0] != '\n']
msa = [x for x in msa if x[0] != '\r']
msa = [x for x in msa if x[0] != '\t']
msa = [x for x in msa if x[0] != '\f']
msa = [x for x in msa if x[0] != '\v']
msa = [x for x in msa if x[0] != '\b']
msa = [x for x in msa if x[0] != '\a']
msa = [x for x in msa if x[0] != '\0']
msa = [x for x in msa if x[0] != '\1']
msa = [x for x in msa if x[0] != '\2']
msa = [x for x in msa if x[0] != '\3']
msa = [x for x in msa if x[0] != '\4']
msa = [x for x in msa if x[0] != '\5']
msa = [x for x in msa if x[0] != '\6']
msa = [x for x in msa if x[0] != '\7']
msa = [x for x in msa if x[0] != '\8']
msa = [x for x in msa if x[0] != '\9']
msa = [x for x in msa if x[0] != '\10']
msa = [x for x in msa if x[0] != '\11']
msa = [x for x in msa if x[0] != '\12']
msa = [x for x in msa if x[0] != '\13']
msa = [x for x in msa if x[0] != '\14']
msa = [x for x in msa if x[0] != '\15']
msa = [x for x in msa if x[0] != '\16']
msa = [x for x in msa if x[0] != '\17']
msa = [x for x in msa if x[0] != '\18']
msa = [x for x in msa if x[0] != '\19']
msa = [x for x in msa if x[0] != '\20']
msa = [x for x in msa if x[0] != '\21']
msa = [x for x in msa if x[0] != '\22']
msa
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
'NoneType' object has no attribute 'text'
bravais
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
[insert]
return nameimport math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
name = None
if group_number in range(1, 3):
name = "triclinic"
elif group_number in range(3, 16):
name = "monoclinic"
elif group_number in range(16, 75):
name = "orthorhombic"
elif group_number in range(75, 143):
name = "tetragonal"
elif group_number in range(143, 168):
name = "trigonal"
elif group_number in range(168, 195):
name = "hexagonal"
elif group_number in range(195, 231):
name = "cubic"
else:
raise ValueError("Invalid space group number")
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
name = None
if group_number in range(1, 3):
name = "triclinic"
elif group_number in range(3, 16):
name = "monoclinic"
elif group_number in range(16, 75):
name = "orthorhombic"
elif group_number in range(75, 143):
name = "tetragonal"
elif group_number in range(143, 168):
name = "trigonal"
elif group_number in range(168, 195):
name = "hexagonal"
elif group_number in range(195, 231):
name = "cubic"
else:
print("Space group number out of range")
sys.exit()
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
name = 'unknown'
if group_number < 3:
name = 'triclinic'
elif group_number < 16:
name = 'monoclinic'
elif group_number < 75:
name = 'orthorhombic'
elif group_number < 143:
name = 'tetragonal'
elif group_number < 168:
name = 'trigonal'
elif group_number < 195:
name = 'hexagonal'
elif group_number < 231:
name = 'cubic'
else:
print('Error: space group number out of range')
sys.exit()
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number < 1 or group_number > 230:
raise ValueError("Invalid space group number")
if group_number <= 2:
name = "triclinic"
elif group_number <= 15:
name = "monoclinic"
elif group_number <= 74:
name = "orthorhombic"
elif group_number <= 142:
name = "tetragonal"
elif group_number <= 167:
name = "trigonal"
elif group_number <= 194:
name = "hexagonal"
else:
name = "cubic"
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number < 1 or group_number > 230:
raise ValueError("Invalid space group number")
lattice_list = [
"triclinic",
"monoclinic",
"orthorhombic",
"tetragonal",
"trigonal",
"hexagonal",
"cubic",
]
return lattice_list[math.floor((group_number - 1) / 16)]
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
canonicalize
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
[insert]
return canon_listimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
carnot_efficiency
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
[insert]
return eps
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - T_cold/T_hot
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
claussius
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
[insert]
return P2
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap/8.314)*(1/T1 - 1/T2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 * math.exp(HVap * (1/T1 - 1/T2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap/8.314)*(1/T1 - 1/T2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap/8.314)*((1/T1)-(1/T2)))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap/8.314)*((1/T1)-(1/T2)))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
compare_electronegativity
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
[insert]
return resultimport math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result=False
if mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity:
result=True
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = False
if mendeleev.element(element1).pauling_electronegativity > mendeleev.element(element2).pauling_electronegativity:
result = True
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'Element' object has no attribute 'pauling_electronegativity'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
condiff_1d
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
[insert]
return diffimport numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
cubes
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
[insert]
return simport math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(n):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
de_broglie
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
[insert]
return limport math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626e-34
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62607004e-34
c = 299792458
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626e-34
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62607004e-34
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
derivative1d-ch
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
[insert]
return dimport numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
derivative_2deg
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
[insert]
return derivimport numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
[insert]
return descriptorsimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append(MoleculeDescriptors.MolecularDescriptorCalculator([x[0] for x in Descriptors._descList]).CalcDescriptors(mol))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append(MoleculeDescriptors.MolecularDescriptorCalculator([x[0] for x in Descriptors._descList]).CalcDescriptors(mol))
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append([
Descriptors.MolWt(mol),
Descriptors.ExactMolWt(mol),
Descriptors.NumValenceElectrons(mol),
Descriptors.NumRadicalElectrons(mol),
Descriptors.NumHDonors(mol),
Descriptors.NumHAcceptors(mol),
Descriptors.TPSA(mol),
Crippen.MolLogP(mol)
])
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append([
Descriptors.MolWt(mol),
Descriptors.ExactMolWt(mol),
Descriptors.NumValenceElectrons(mol),
Descriptors.NumRadicalElectrons(mol),
Descriptors.NumHDonors(mol),
Descriptors.NumHAcceptors(mol),
Descriptors.TPSA(mol),
Descriptors.LabuteASA(mol)
])
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append(MoleculeDescriptors.MolecularDescriptorCalculator([x[0] for x in Descriptors._descList]).CalcDescriptors(mol))
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
dipole
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
[insert]
return dipole_momentimport numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(len(charges)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(len(charges)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(len(charges)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.sum(coordinates * charges[:, np.newaxis], axis=0)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.sum(coordinates * charges[:, np.newaxis], axis=0)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
dou
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
[insert]
return dimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
d = Descriptors.NumRadicalElectrons(mol)
return d
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
return rdMolDescriptors.CalcNumRotatableBonds(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
d = Descriptors.NumRadicalElectrons(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
m = Chem.MolFromSmiles(smiles)
d = Descriptors.NumHAcceptors(m) + Descriptors.NumHDonors(m) + Descriptors.NumRotatableBonds(m)
return d
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
return Descriptors.NumRotatableBonds(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
eigen-ch
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
eigen
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
[insert]
return w,vimport numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
element_mass
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
[insert]
return massimport math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print("Error: element mass not found")
sys.exit()
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print "Error: element mass not found"
sys.exit()
else:
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Missing parentheses in call to 'print'. Did you mean print("Error: element mass not found")? (<string>, line 12)
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print "Error: element mass for %s not found" % element_symbol
sys.exit(1)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Missing parentheses in call to 'print'. Did you mean print("Error: element mass for %s not found" % element_symbol)? (<string>, line 12)
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print "Error: element mass not found for element: ", element_symbol
sys.exit(1)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Missing parentheses in call to 'print'. Did you mean print("Error: element mass not found for element: ", element_symbol)? (<string>, line 12)
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print("Error: element symbol not found")
sys.exit()
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
element_name
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
[insert]
return simport math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
s = s.lower()
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
energy_of_e
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
[insert]
return energyimport math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6 * (1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
find_indices
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
[insert]
return idximport mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
top = traj.topology
idx = top.select('name CA')
idx = idx[:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
top = traj.topology
idx = top.select('name CA')
idx = idx[:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
idx = np.where(traj.top.select('name CA'))[0]
idx = idx[:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
top = traj.topology
idx = top.select('name CA')
idx = idx[:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
idx = topology.select("name CA")
idx = idx[0:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
force_constant
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
[insert]
return kimport numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.0/4.0)*(wave_len*(1.0/100.0))**2*(m1*m2)/(m1+m2)
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (4*np.pi**2*m1*m2)/(wave_len*(m1+m2))
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.0/wave_len)*(1.0/wave_len)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1.0/100.0)*(1
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (2*np.pi*1.98644568e-23*1e-23*1e-2*wave_len)**2/(m1*m2)
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (m1*m2)/(m1+m2)*(wave_len*1.0e2)**2*1.0e-8
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
fourier_1d
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
[insert]
return wimport numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
w = np.zeros(N, dtype=np.complex)
for k in range(N):
for n in range(N):
w[k] += x[n]*np.exp(-2j*np.pi*k*n/N)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = x.shape[0]
w = np.zeros(N, dtype=np.complex)
for k in range(N):
for n in range(N):
w[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
w = np.zeros(N, dtype=complex)
for k in range(N):
for n in range(N):
w[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
freezing_depression
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
[insert]
return deltaTimport math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
genpos
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
[insert]
return generatorsimport requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all('table')[0]
generators = []
for row in table.find_all('tr')[1:]:
cols = row.find_all('td')
generators.append(np.array([[float(cols[1].text), float(cols[2].text), float(cols[3].text)],
[float(cols[4].text), float(cols[5].text), float(cols[6].text)],
[float(cols[7].text), float(cols[8].text), float(cols[9].text)]]))
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matgen?gnum=' + str(gnum)
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
table = soup.find_all('table')[0]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
generators = np.array(generators)
generators = generators[:,1:]
generators = generators.astype(float)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-gen-matrices?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all('table')[0]
generators = []
for row in table.find_all('tr')[1:]:
generators.append(np.array([float(x.text) for x in row.find_all('td')[1:]]))
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matgen?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all('table')[2]
generators = []
for row in table.find_all('tr')[1:]:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append(np.array([[float(cols[1]), float(cols[2]), float(cols[3])],
[float(cols[4]), float(cols[5]), float(cols[6])],
[float(cols[7]), float(cols[8]), float(cols[9])]]))
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum=" + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
table = soup.find_all("table")[0]
generators = []
for row in table.find_all("tr")[1:]:
generators.append(np.array([float(x.text) for x in row.find_all("td")[1:]]))
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
heating_water
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
[insert]
return q
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * (T2 - T1) * 4.184
print(q)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * (T2 - T1) * 4.184
print("The energy required to heat", n, "moles of water from", T1, "to", T2, "is", q, "kcal")
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * (T2 - T1) * 4.184
print(q)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * 4.184 * (T2 - T1)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * (T2 - T1) * 4.184
print("The energy required to heat", n, "moles of water from", T1, "to", T2, "is", q, "kcal")
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
hydrophobic_res
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
[insert]
return residsimport mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i in range(traj.n_residues):
if traj.topology.residue(i).is_hydrophobic:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i, res in enumerate(traj.topology.residues):
if res.is_water:
continue
if res.name in ['ALA', 'VAL', 'LEU', 'ILE', 'PHE', 'TYR', 'TRP', 'MET']:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
Success
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for res in traj.topology.residues:
if res.is_water:
continue
if res.name in ['VAL', 'ILE', 'LEU', 'PHE', 'TYR', 'TRP', 'MET']:
resids.append(res.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
Success
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i, res in enumerate(traj.topology.residues):
if res.is_water:
continue
if res.is_protein:
if res.name in ['ALA', 'VAL', 'LEU', 'ILE', 'MET', 'PHE', 'TRP', 'PRO']:
resids.append(i)
resids = np.array(resids)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i in range(traj.n_residues):
if traj.topology.residue(i).is_hydrophobic:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
ideal_gas
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
[insert]
return Pimport math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08206 # L atm / mol K
P = (n * R * T) / V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm L / mol K
P = (n * R * T) / V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08206 # L atm mol^-1 K^-1
P = (n*R*T)/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm*L/mol/K
P = n*R*T/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 #L atm / mol K
P = n*R*T/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
integral
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
[insert]
return integralimport numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = (a/5)*(b**5 - d**5) + (b/4)*(c**4 - d**4) + (c/3)*(d**3 - b**3) + (d/2)*(b**2 - c**2)
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = (a/4)*(b**4) + (b/3)*(b**3) + (c/2)*(b**2) + d*b
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = a*(b**2)/2 + c*b + d*np.log(b)
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = a*(b**2)/2 + b*c + c*d + d**2/2
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = (a*b**2)/3 + (a*b*c)/2 + a*d - (b**3*c)/3 + (b**2*c**2)/2 - b**2*d + (b*c**3)/3 - b*c*d + (c**4)/4 - c**2*d + d**2
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
trap
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
[insert]
return integralimport numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
integral = 0.5 * f(a) + 0.5 * f(b)
for i in range(1, n):
integral += f(a + i * h)
integral *= h
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
h = (b-a)/n
for i in range(1, n):
integral += f(a + i*h)
integral = h/2*(f(a) + 2*integral + f(b))
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
integral = 0.5 * h * (f(a) + f(b))
for i in range(1, n):
integral += h * f(a + i * h)
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
integral = 0.5*f(a) + 0.5*f(b)
for i in range(1, n):
integral += f(a + i*h)
integral *= h
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
x = np.linspace(a, b, n+1)
integral = 0.5*h*(f(a) + f(b))
for i in range(1, n):
integral += h*f(x[i])
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
invert_matrix
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
[insert]
return Ainvimport numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
iupac2smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
[insert]
return SMILESimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
SMILES = Chem.MolToSmiles(mol)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
SMILES = Chem.MolToSmiles(mol)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
SMILES = Chem.MolToSmiles(mol)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
kld
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
[insert]
return lossimport numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(true_data * np.log(true_data / predicted_data))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
langevin_dynamics
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
[insert]
return x_traj, v_trajimport numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
v_traj[i] = v_traj[i-1] - (gamma/m)*v_traj[i-1]*dt - (F(x_traj[i-1])/m)*dt + np.sqrt(2*gamma*T/m)*np.sqrt(dt)*np.random.randn()
x_traj[i] = x_traj[i-1] + v_traj[i]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x = x0
v = v0
for i in range(n_steps):
x_traj[i] = x
v_traj[i] = v
x += v*dt
v += (-gamma*v + F(x) - np.random.normal(0,np.sqrt(2*gamma*T/m)))/m*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*v_traj[i-1]
v_traj[i] = v_traj[i-1] - dt*gamma*v_traj[i-1] - dt*F(x_traj[i-1])/m + np.sqrt(2*gamma*T*dt)*np.random.normal()
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt + (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T*dt/m)*np.random.normal(0,1)
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = (v_traj[i] - F(x_traj[i])/m*dt - gamma*v_traj[i]*dt + np.sqrt(2*gamma*T*dt)*np.random.normal())/(1+gamma*dt)
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
weighted-least-squares
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
[insert]
return betaimport numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = np.linalg.inv(x.T * w * x) * x.T * w * y
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = (x.T * w * x).I * x.T * w * y
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.inv(x.T.dot(np.diag(w)).dot(x)).dot(x.T).dot(np.diag(w)).dot(y)
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
Success
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = np.linalg.inv(x.T * w * x) * x.T * w * y
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = (x.T * w * x).I * x.T * w * y
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
lipinski_rule_of_five
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
[insert]
return resultimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
hbd = rdMolDescriptors.CalcNumHBD(mol)
hba = rdMolDescriptors.CalcNumHBA(mol)
mw = Descriptors.MolWt(mol)
logp = Crippen.MolLogP(mol)
result = True
if hbd > 5:
result = False
if hba > 10:
result = False
if mw > 500:
result = False
if logp > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
mape
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
[insert]
return eimport math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += math.fabs((y_hat[i] - y[i])/y[i])
e = e/len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs(y_hat[i]-y[i])/y[i]
e /= len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs(y_hat[i]-y[i])/y[i]
e = e/len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs(y_hat[i]-y[i])/y[i]
e = e/len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs(y_hat[i] - y[i]) / y[i]
e /= len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
mapping_operator
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
[insert]
return Mimport MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.n_atoms, len(beads_mappings)))
for i, bead in enumerate(beads_mappings):
M[bead.indices, i] = bead.masses
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'masses'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(molecule.atoms), len(beads_mappings)))
for i, beads in enumerate(beads_mappings):
M[beads.indices, i] = 1.0
M = np.diag(molecule.masses) @ M
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'indices'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.n_atoms, len(beads_mappings)))
for i, bead in enumerate(beads_mappings):
M[bead.indices, i] = bead.masses / bead.masses.sum()
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'masses'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), molecule.n_atoms))
for i, bead in enumerate(beads_mappings):
M[i, bead.indices] = bead.masses / bead.masses.sum()
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'masses'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(molecule.atoms), len(beads_mappings)))
for i, bead in enumerate(beads_mappings):
M[bead.indices, i] = bead.masses
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'masses'
matpow
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
[insert]
return rimport numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
while n > 0:
if n & 1:
r = np.dot(r,x)
x = np.dot(x,x)
n >>= 1
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
matrix_factorial
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
[insert]
return fimport numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
max-boltz
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
[insert]
return simport math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.38064852e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.38064852e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
michaelis
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
[insert]
return v
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax*S/(Km+S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S / (Km + S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S / (Km + S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax*S/(Km + S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax*S/(Km+S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
mol_charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
[insert]
return chargeimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = 0
for atom in mol.GetAtoms():
charge += atom.GetFormalCharge()
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = 0
for atom in mol.GetAtoms():
charge += atom.GetFormalCharge()
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
net_charge
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
[insert]
return chargeimport math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in sequence:
if i == 'R' or i == 'K':
charge += 1
elif i == 'D' or i == 'E':
charge -= 1
else:
charge += 0
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in sequence:
if i == 'R' or i == 'K':
charge += 1
elif i == 'D' or i == 'E':
charge -= 1
else:
charge += 0
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
else:
continue
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in range(len(sequence)):
if sequence[i] == 'R' or sequence[i] == 'K':
charge += 1
elif sequence[i] == 'D' or sequence[i] == 'E':
charge -= 1
else:
charge += 0
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
solve_ode
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
[insert]
return solimport numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
y = np.zeros((len(t), len(y0)))
y[0] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = h*fn(t[i], y[i])
k2 = h*fn(t[i] + h/4, y[i] + k1/4)
k3 = h*fn(t[i] + 3*h/8, y[i] + 3*k1/32 + 9*k2/32)
k4 = h*fn(t[i] + 12*h/13, y[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h*fn(t[i] + h, y[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h*fn(t[i] + h/2, y[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1] = y[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
sol = y
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
n = len(t)
y = np.zeros((n, len(y0)))
y[0] = y0
for i in range(n-1):
h = t[i+1] - t[i]
k1 = h * fn(t[i], y[i])
k2 = h * fn(t[i] + h/4, y[i] + k1/4)
k3 = h * fn(t[i] + 3*h/8, y[i] + 3*k1/32 + 9*k2/32)
k4 = h * fn(t[i] + 12*h/13, y[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h * fn(t[i] + h, y[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h * fn(t[i] + h/2, y[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1] = y[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
sol = y
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
n = len(t)
y = np.zeros((n, len(y0)))
y[0] = y0
for i in range(n-1):
h = t[i+1] - t[i]
k1 = h * fn(t[i], y[i])
k2 = h * fn(t[i] + h/4, y[i] + k1/4)
k3 = h * fn(t[i] + 3*h/8, y[i] + 3*k1/32 + 9*k2/32)
k4 = h * fn(t[i] + 12*h/13, y[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h * fn(t[i] + h, y[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h * fn(t[i] + h/2, y[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1] = y[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
sol = y
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros((len(t), len(y0)))
sol[0,:] = y0
for i in range(1, len(t)):
h = t[i] - t[i-1]
k1 = fn(t[i-1], sol[i-1,:])
k2 = fn(t[i-1] + h/4, sol[i-1,:] + h/4*k1)
k3 = fn(t[i-1] + 3*h/8, sol[i-1,:] + 3*h/32*k1 + 9*h/32*k2)
k4 = fn(t[i-1] + 12*h/13, sol[i-1,:] + 1932*h/2197*k1 - 7200*h/2197*k2 + 7296*h/2197*k3)
k5 = fn(t[i-1] + h, sol[i-1,:] + 439*h/216*k1 - 8*h*k2 + 3680*h/513*k3 - 845*h/4104*k4)
k6 = fn(t[i-1] + h/2, sol[i-1,:] - 8*h/27*k1 + 2*h*k2 - 3544*h/2565*k3 + 1859*h/4104*k4 - 11*h/40*k5)
sol[i,:] = sol[i-1,:] + h/6*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
t = np.asarray(t)
y = np.asarray(y0)
sol = np.zeros((len(t), len(y0)))
sol[0] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = h*fn(t[i], y)
k2 = h*fn(t[i] + h/4, y + k1/4)
k3 = h*fn(t[i] + 3*h/8, y + 3*k1/32 + 9*k2/32)
k4 = h*fn(t[i] + 12*h/13, y + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h*fn(t[i] + h, y + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h*fn(t[i] + h/2, y - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y = y + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
sol[i+1] = y
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
ohe
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
[insert]
return vimport numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(np.unique(a))))
for i in range(len(a)):
v[i, np.where(np.unique(a) == a[i])[0]] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
Success
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, k in enumerate(a):
v[i, k] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, s in enumerate(a):
v[i, s] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, c in enumerate(a):
v[i, c] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, k in enumerate(a):
v[i, k] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
osmotic_pressure
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
[insert]
return pimport math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = (Pi*R*T)/(1.0-Pi*R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
pair_wise
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
[insert]
return distancesimport mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
alpha_carbons = traj.topology.select("name CA")
distances = md.compute_distances(traj, alpha_carbons, alpha_carbons)
distances = np.triu(distances)
distances = distances[np.nonzero(distances)]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
topology = traj.topology
alpha_carbons = topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = distances[0]
distances = distances[np.triu_indices(len(alpha_carbons), k=1)]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
topology = traj.topology
alpha_carbons = topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, alpha_carbons)
distances = np.triu(distances)
distances = distances[distances != 0]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
alpha_carbons = traj.topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, alpha_carbons)
distances = np.triu(distances)
distances = distances[np.nonzero(distances)]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
topology = traj.topology
alpha_carbons = topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = distances[:, np.triu_indices(len(alpha_carbons), k=1)]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
pi
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
[insert]
return pi_estimport numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.rand(nsamples)
y = np.random.rand(nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4.0 * np.sum(r<1.0) / nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4*np.sum(r<1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4*np.sum(r<1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4*np.sum(r<1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
pi_est = 4*np.sum(x**2 + y**2 < 1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
pib_1d
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
[insert]
return eimport math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
pred_interval
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
[insert]
return nimport numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = np.log(1-pred_level)/np.log(1-p)
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = np.ceil(np.log(1-pred_level)/np.log(1-p))
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = np.ceil(np.log(1-pred_level)/np.log(1-p))
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = np.ceil(np.log(1-pred_level)/np.log(1-p))
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = np.ceil(np.log(1-pred_level)/np.log(1-p))
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
pubchem
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
[insert]
return molsimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
# Get the CID of the molecule
r = requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles)
cid = r.text.split('\n')[0]
# Get the similar molecules
r = requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/similarity/XML' % cid)
mols = set()
for mol in r.text.split('\n'):
if '<PC-AssaySimilarity>' in mol:
mols.add(mol.split('>')[1].split('<')[0])
return mols
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
# Get the CID of the input molecule
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/{}/cids/TXT".format(smiles)
r = requests.get(url)
cid = r.text.split()[0]
# Get the CIDs of molecules with greater than 80% similarity
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/similarity/XML".format(cid)
r = requests.get(url)
cids = [x.text for x in r.xml.findall(".//CID")]
# Get the SMILES strings of the similar molecules
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/property/CanonicalSMILES/TXT".format(",".join(cids))
r = requests.get(url)
smiles = r.text.split()
return smiles
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
'Response' object has no attribute 'xml'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles
response = requests.get(url)
cids = response.text.split('\n')
cids = [cid for cid in cids if cid]
cids = ','.join(cids)
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT' % cids
response = requests.get(url)
mols = response.text.split('\n')
mols = [mol for mol in mols if mol]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles
response = requests.get(url)
cids = response.text.split('\n')
cids = [cid for cid in cids if cid != '']
cids = ','.join(cids)
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT' % cids
response = requests.get(url)
mols = response.text.split('\n')
mols = [mol for mol in mols if mol != '']
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/smiles/'
payload = {'smiles': smiles, 'threshold': '80', 'sids': '1', 'aids': '1', 'cids': '1', 'format': 'json'}
r = requests.get(url, params=payload)
mols = set()
for mol in r.json()['PC_Compounds']:
mols.add(mol['props']['CanonicalSMILES'])
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Expecting value: line 1 column 1 (char 0)
pyscf_energy
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
[insert]
return ground_energyimport pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
ground_energy = mf.e_tot
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
ground_energy = mf.e_tot
return ground_energy
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
ground_energy = mf.e_tot
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
print(ground_energy)
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
print("The ground state energy for {} is {}".format(atom,ground_energy))
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
qed
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
[insert]
return resultimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
quantile
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
[insert]
return resultimport numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.percentile(a, q * 100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
a = np.array(a)
result = np.zeros(len(q))
for i in range(len(q)):
result[i] = np.percentile(a, q[i]*100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
Success
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.percentile(a, q * 100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.percentile(a, q*100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
a = np.array(a)
result = np.percentile(a, q * 100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
random_walk
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
[insert]
return trajimport numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
traj[i] = x0 + a*np.random.choice([-1,1])
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Timeout
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
traj[i] = x0
x0 += a*(np.random.randint(2)*2-1)
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
traj[i] = x0
x0 += a*(2*np.random.randint(2)-1)
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
traj[i] = x0 + a*np.random.choice([-1,1])
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Timeout
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
traj[i] = x0
x0 += a*np.random.choice([-1,1])
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Timeout
rank
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
[insert]
return rimport numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-15)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
remove-water
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
[insert]
return new_trajimport mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(top.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(top.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(top.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(top.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(top.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
rms_velocity
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
[insert]
return v_rms
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 #J/K
m = m*1.66054e-24 #g to kg
v_rms = math.sqrt((3*k*T)/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
m = m * 1.66053904e-27 # mass in kg
v_rms = math.sqrt(3*k*T/m)
v_rms = v_rms * 1e-3 # m/s to km/s
v_rms = round(v_rms,2)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.3806488e-23
m = m * 1.66053892e-27
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23
m = m*1.6605e-27
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
rmse
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
[insert]
return eimport numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
rog
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
[insert]
return rgimport mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
rg = np.mean(rg)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
rg = np.mean(rg)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
sasa
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
[insert]
return sasaimport mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = np.sum(sasa, axis=1)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj, mode='residue')
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj, mode='residue')
sasa = np.array(sasa)
sasa = sasa.flatten()
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj, mode='residue')
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
scaffold
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
[insert]
return scaffold_smilesimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(smiles)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(smiles)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Scaffolds.MurckoScaffoldSmilesFromSmiles(smiles)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmilesFromSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Chem.MolToSmiles(Scaffolds.MurckoScaffoldSmiles(mol))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(mol)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
seq-align
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
[insert]
return alignedfrom Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
seq-trans
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
[insert]
return prot_seqfrom Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = gene_seq.translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
translate() takes exactly one argument (0 given)
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
sequence
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
[insert]
return ximport numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.logspace(np.log10(s),np.log10(e),l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.logspace(np.log10(s),np.log10(e),l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.logspace(np.log10(s),np.log10(e),l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.logspace(np.log10(s),np.log10(e),l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.array([s])
while x[-1] < e:
x = np.append(x,x[-1]*l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
sle
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
[insert]
return ximport sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
spectral_r
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
[insert]
return sradiusimport numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.max(np.abs(np.linalg.eigvals(a)))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigvals = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigvals))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigenvalues = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigenvalues))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigenvalues = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigenvalues))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigval = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigval))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
find_peaks
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
[insert]
return wavenumbersimport numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
wavenumbers = []
for i in range(npeaks):
peak_index = np.argmax(abs_spectrum[:, 1])
peak_wavenumber = abs_spectrum[peak_index, 0]
wavenumbers.append(peak_wavenumber)
abs_spectrum[peak_index, 1] = 0
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0.1)
peak_wavenumbers = abs_spectrum[peaks, 0]
peak_wavenumbers.sort()
return peak_wavenumbers[-npeaks:]
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0.1)[0]
peaks = peaks[np.argsort(abs_spectrum[peaks, 1])][::-1]
peaks = peaks[:npeaks]
wavenumbers = abs_spectrum[peaks, 0]
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
wavenumbers = []
for i in range(npeaks):
max_idx = np.argmax(abs_spectrum[:, 1])
wavenumbers.append(abs_spectrum[max_idx, 0])
abs_spectrum[max_idx, 1] = 0
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0.1)
# Sort by peak height
peaks = peaks[np.argsort(abs_spectrum[peaks, 1])[::-1]]
# Return wavenumbers
wavenumbers = abs_spectrum[peaks, 0][:npeaks]
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
speed_of_sound
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
[insert]
return s
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 #J/mol/K
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R=8.314
s=math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 #J/mol/K
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
substructure
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
[insert]
return idximport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i, mol in enumerate(mol_list):
if mol.HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
tanimoto
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
[insert]
return simport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(smiles) for smiles in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits) for mol in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i, fp1 in enumerate(fps):
for j, fp2 in enumerate(fps):
tanimoto_matrix[i, j] = DataStructs.FingerprintSimilarity(fp1, fp2)
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(smiles) for smiles in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits) for mol in mols]
s = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(i, len(fps)):
s[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
s[j, i] = s[i, j]
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(s) for s in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(m, 2, nBits=bits) for m in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(i, len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
tanimoto_matrix[j, i] = tanimoto_matrix[i, j]
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(smi) for smi in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(m, 2, nBits=bits) for m in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(smiles) for smiles in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits) for mol in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i, j] = DataStructs.FingerprintSimilarity(fps[i], fps[j])
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
unbdistance
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
[insert]
return resultimport mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_idx = traj.topology.select('resname '+lig_str)
protein_idx = traj.topology.select('protein')
result = md.compute_distances(traj,[[0,0]],
periodic=False,
opt=True,
indices=[[protein_idx.mean(),lig_idx.mean()]])
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_ind = traj.topology.select('resname ' + lig_str)
protein_ind = traj.topology.select('protein')
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
protein_com = md.compute_center_of_mass(traj.atom_slice(protein_ind))
result = np.linalg.norm(lig_com - protein_com,axis=1)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_ind = traj.topology.select('resname '+lig_str)
protein_ind = traj.topology.select('protein')
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
protein_com = md.compute_center_of_mass(traj.atom_slice(protein_ind))
result = np.linalg.norm(lig_com-protein_com,axis=1)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the indices of the ligand
lig_ind = traj.topology.select('resname ' + lig_str)
# get the indices of the protein
prot_ind = traj.topology.select('protein')
# get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# compute the distance between the two
result = md.compute_distances(traj,np.array([[0,1]]),
periodic=False,opt=True)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_ind = traj.topology.select('resname '+lig_str)
prot_ind = traj.topology.select('protein')
result = []
for i in range(traj.n_frames):
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))[i]
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))[i]
result.append(np.linalg.norm(lig_com-prot_com))
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
| Test | Run 0 | Run 1 | Run 2 | Run 3 | Run 4 |
|---|---|---|---|---|---|
| aa_polarity | Pass | Fail | Fail | Pass | Pass |
| adiabatic_expansion | Pass | Pass | Pass | Pass | Pass |
| alignment | Fail | Fail | Fail | Fail | Fail |
| angle | Pass | Pass | Fail | Pass | Pass |
| aromatic_aa | Pass | Pass | Pass | Pass | Pass |
| arrhenius | Pass | Fail | Fail | Pass | Pass |
| bimolecular | Pass | Pass | Pass | Pass | Pass |
| bb_rad | Pass | Pass | Pass | Pass | Pass |
| blast | Fail | Fail | Fail | Fail | Fail |
| bravais | Fail | Fail | Fail | Fail | Fail |
| canonicalize | Pass | Pass | Pass | Pass | Pass |
| carnot_efficiency | Pass | Pass | Pass | Pass | Pass |
| claussius | Pass | Pass | Fail | Fail | Pass |
| compare_electronegativity | Fail | Fail | Fail | Fail | Fail |
| condiff_1d | Pass | Pass | Pass | Pass | Pass |
| cubes | Fail | Fail | Pass | Fail | Fail |
| de_broglie | Pass | Pass | Pass | Pass | Pass |
| derivative1d-ch | Pass | Pass | Pass | Fail | Pass |
| derivative_2deg | Pass | Pass | Pass | Pass | Pass |
| descriptors | Fail | Fail | Fail | Fail | Fail |
| dipole | Pass | Pass | Pass | Pass | Fail |
| dou | Fail | Fail | Fail | Fail | Fail |
| eigen-ch | Pass | Pass | Pass | Pass | Pass |
| eigen | Pass | Pass | Pass | Pass | Pass |
| element_mass | Pass | Pass | Pass | Pass | Pass |
| element_name | Pass | Pass | Pass | Pass | Pass |
| energy_of_e | Fail | Fail | Fail | Pass | Fail |
| find_indices | Fail | Fail | Fail | Fail | Fail |
| force_constant | Fail | Fail | Fail | Fail | Fail |
| fourier_1d | Pass | Fail | Pass | Fail | Fail |
| freezing_depression | Pass | Pass | Pass | Pass | Pass |
| genpos | Fail | Fail | Fail | Fail | Fail |
| heating_water | Fail | Fail | Fail | Fail | Fail |
| hydrophobic_res | Fail | Fail | Fail | Fail | Fail |
| ideal_gas | Pass | Pass | Pass | Pass | Pass |
| integral | Fail | Fail | Fail | Fail | Fail |
| trap | Pass | Pass | Pass | Pass | Pass |
| invert_matrix | Fail | Pass | Fail | Pass | Pass |
| iupac2smiles | Fail | Fail | Fail | Fail | Fail |
| kld | Fail | Fail | Fail | Fail | Fail |
| langevin_dynamics | Fail | Fail | Fail | Fail | Fail |
| weighted-least-squares | Pass | Fail | Fail | Fail | Fail |
| lipinski_rule_of_five | Pass | Pass | Pass | Fail | Pass |
| mape | Fail | Pass | Pass | Fail | Fail |
| mapping_operator | Fail | Fail | Fail | Fail | Fail |
| matpow | Fail | Pass | Fail | Pass | Pass |
| matrix_factorial | Fail | Fail | Fail | Fail | Fail |
| max-boltz | Pass | Fail | Fail | Pass | Pass |
| michaelis | Pass | Pass | Pass | Pass | Pass |
| mol_charge | Fail | Pass | Pass | Pass | Pass |
| net_charge | Pass | Pass | Pass | Pass | Pass |
| solve_ode | Fail | Fail | Fail | Fail | Fail |
| ohe | Fail | Fail | Fail | Fail | Fail |
| osmotic_pressure | Pass | Pass | Pass | Pass | Pass |
| pair_wise | Fail | Fail | Fail | Fail | Fail |
| pi | Pass | Pass | Pass | Pass | Pass |
| pib_1d | Pass | Pass | Pass | Pass | Fail |
| pred_interval | Pass | Pass | Pass | Pass | Pass |
| pubchem | Fail | Fail | Fail | Fail | Fail |
| pyscf_energy | Fail | Fail | Fail | Fail | Fail |
| qed | Pass | Fail | Pass | Pass | Pass |
| quantile | Pass | Fail | Fail | Fail | Pass |
| random_walk | Fail | Pass | Pass | Fail | Pass |
| rank | Pass | Pass | Pass | Pass | Pass |
| remove-water | Pass | Pass | Pass | Pass | Pass |
| rms_velocity | Fail | Fail | Fail | Fail | Fail |
| rmse | Pass | Pass | Pass | Pass | Pass |
| rog | Pass | Pass | Pass | Pass | Pass |
| sasa | Fail | Pass | Pass | Fail | Fail |
| scaffold | Fail | Fail | Fail | Fail | Fail |
| seq-align | Pass | Pass | Fail | Pass | Pass |
| seq-trans | Pass | Pass | Pass | Pass | Pass |
| sequence | Pass | Pass | Pass | Fail | Pass |
| sle | Fail | Fail | Fail | Fail | Fail |
| spectral_r | Pass | Fail | Fail | Pass | Fail |
| find_peaks | Fail | Fail | Fail | Fail | Fail |
| speed_of_sound | Fail | Fail | Fail | Fail | Fail |
| substructure | Fail | Fail | Fail | Fail | Fail |
| tanimoto | Pass | Pass | Pass | Pass | Pass |
| unbdistance | Fail | Fail | Fail | Fail | Fail |
aa_polarity
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar = ['S', 'T', 'Y', 'C', 'N', 'Q']
count = 0
for i in sequence:
if i in polar:
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for amino_acid in sequence:
if amino_acid in ['R', 'K', 'D', 'E', 'Q', 'N', 'H', 'S', 'T', 'Y']:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for i in range(len(sequence)):
if sequence[i] == 'R' or sequence[i] == 'K' or sequence[i] == 'N' or sequence[i] == 'Q':
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for aa in sequence:
if aa in ['S', 'T', 'N', 'Q']:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for amino_acid in sequence:
if amino_acid in ['S', 'T', 'N', 'Q']:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
adiabatic_expansion
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 * (P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 * (P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 * (P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
alignment
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# Align the trajectory to a specific frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align trajectory to a specific frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to the first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to the first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
angle
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
cos_angle = np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2))
angle = np.arccos(cos_angle)
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
aromatic_aa
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_aa = ['F', 'Y', 'W']
count = 0
for aa in sequence:
if aa in aromatic_aa:
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_residues = ['F', 'Y', 'W']
aromatic_count = 0
for aa in sequence:
if aa in aromatic_residues:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_residues = ['F', 'Y', 'W']
aromatic_count = 0
for residue in sequence:
if residue in aromatic_residues:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_aa = ['F', 'Y', 'W']
aromatic_count = 0
for aa in sequence:
if aa in aromatic_aa:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_aa = ['F', 'Y', 'W']
aromatic_count = 0
for aa in sequence:
if aa in aromatic_aa:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
arrhenius
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
R = 8.314 # J/mol/K
return k2 * math.exp((Ea/R)*(1/T2 - 1/T1))
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
R = 8.314
k1 = k2 * math.exp((Ea/R)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
R = 8.314 # J/mol/K
return k2 * math.exp((Ea/R)*(1/T1 - 1/T2))
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
R = 8.314 # J/mol/K
k1 = k2 * math.exp((Ea/R) * (1/T2 - 1/T1))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
R = 8.314 # J/mol/K
k1 = k2 * math.exp((Ea / R) * ((1 / T2) - (1 / T1)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
bimolecular
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
bb_rad
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
# start
h = 6.62607004e-34
c = 299792458
k = 1.38064852e-23
b = 2*h*c**2/lam**5
a = h*c/(lam*k*T)
return b/(np.exp(a)-1)
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.62607004e-34 # Planck's constant
c = 299792458 # speed of light
k = 1.38064852e-23 # Boltzmann constant
return 2*h*c**2/(lam**5*(np.exp(h*c/(lam*k*T))-1))
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
return 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
# Your code here
h = 6.626e-34
c = 3.0e8
k = 1.38e-23
a = 2.0*h*c**2
b = h*c/(lam*k*T)
intensity = a/ ( (lam**5) * (np.exp(b) - 1.0) )
return intensity
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
return 2*h*c**2/(lam**5*(np.exp(h*c/(lam*k*T))-1))
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
blast
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'http://www.uniprot.org/blast/'
params = {'query': seq, 'format': 'fasta'}
r = requests.post(url, data=params)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
# 4. Parse MSA
msa = soup.find('pre').text
# 5. Return a tuple of e score, id of top match
return msa
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
'NoneType' object has no attribute 'text'
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'http://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'QUERY': seq, 'DATABASE': 'nr', 'PROGRAM': 'blastp',
'FILTER': 'L', 'EXPECT': '10', 'HITLIST_SIZE': '1',
'CMD': 'Put'}
r = requests.get(url, params=params)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
result = soup.find('pre').text
# 4. Parse MSA
msa = result.split('Query=')[-1].split('\n\n')[0]
msa = msa.split('\n')
msa = [x for x in msa if x]
msa = [x.split() for x in msa]
msa = np.array(msa)
# 5. Return a tuple of e score, id of top match
e_score = msa[-1][-1]
id = msa[1][1]
return (e_score, id)
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
'NoneType' object has no attribute 'text'
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
from Bio.Blast import NCBIWWW
from Bio.Blast import NCBIXML
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
from Bio.Align.Applications import ClustalwCommandline
from Bio import AlignIO
from Bio.Align import AlignInfo
from Bio import Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator
from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
from Bio.Phylo.TreeConstruction import _DistanceMatrix
from Bio import Entrez
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
from Bio.Align.Applications import ClustalwCommandline
from Bio import AlignIO
from Bio.Align import AlignInfo
from Bio import Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator
from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
from Bio.Phylo.TreeConstruction import _DistanceMatrix
from Bio import Entrez
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
from Bio.Align.Applications import ClustalwCommandline
from Bio import AlignIO
from Bio.Align import AlignInfo
from Bio import Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator
from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
from Bio.Phylo.TreeConstruction import _DistanceMatrix
from Bio import Entrez
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
from Bio.Align.Applications import ClustalwCommandline
from Bio import AlignIO
from Bio.Align import AlignInfo
from Bio import Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator
from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
from Bio.Phylo.TreeConstruction import _DistanceMatrix
from Bio import Entrez
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
from Bio.Align.Applications import ClustalwCommandline
from Bio import AlignIO
from Bio.Align import AlignInfo
from Bio import Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator
from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
from Bio.Phylo.TreeConstruction import _DistanceMatrix
from Bio import Entrez
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
from Bio.Align.Applications import ClustalwCommandline
from Bio import AlignIO
from Bio.Align import AlignInfo
from Bio import Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator
from Bio.Phylo.TreeConstruction import DistanceTreeConstructor
from Bio.Phylo.TreeConstruction import _DistanceMatrix
from Bio import Entrez
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
invalid syntax (<string>, line 101)
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'http://blast.ncbi.nlm.nih.gov/Blast.cgi'
payload = {'QUERY': seq,
'PROGRAM': 'blastp',
'DATABASE': 'nr',
'CMD': 'Put',
'PAGE': 'Nucleotides',
'FILTER': 'L',
'EXPECT': '10',
'HITLIST_SIZE': '1',
'ALIGNMENTS': '1',
'DESCRIPTIONS': '1',
'FORMAT_TYPE': 'HTML',
'NCBI_GI': 'on',
'SHOW_OVERVIEW': 'on',
'FORMAT_OBJECT': 'Alignment',
'CLIENT': 'web',
'SERVICE': 'plain',
'NCBI_GI': 'on',
'PAGE': 'Nucleotides',
'CMD': 'Put',
'RID': '',
'FORMAT_TYPE': 'HTML',
'PROGRAM': 'blastp',
'DATABASE': 'nr',
'QUERY': seq,
'EXPECT': '10',
'HITLIST_SIZE': '1',
'ALIGNMENTS': '1',
'DESCRIPTIONS': '1',
'FORMAT_TYPE': 'HTML',
'NCBI_GI': 'on',
'SHOW_OVERVIEW': 'on',
'FORMAT_OBJECT': 'Alignment',
'CLIENT': 'web',
'SERVICE': 'plain',
'NCBI_GI': 'on',
'PAGE': 'Nucleotides',
'CMD': 'Put',
'RID': '',
'FORMAT_TYPE': 'HTML',
'PROGRAM': 'blastp',
'DATABASE': 'nr',
'QUERY': seq,
'EXPECT': '10',
'HITLIST_SIZE': '1',
'ALIGNMENTS': '1',
'DESCRIPTIONS': '1',
'FORMAT_TYPE': 'HTML',
'NCBI_GI': 'on',
'SHOW_OVERVIEW': 'on',
'FORMAT_OBJECT': 'Alignment',
'CLIENT': 'web',
'SERVICE': 'plain',
'NCBI_GI': 'on',
'PAGE': 'Nucleotides',
'CMD': 'Put',
'RID': '',
'FORMAT_TYPE': 'HTML',
'PROGRAM': 'blastp',
'DATABASE': 'nr',
'QUERY': seq,
'EXPECT': '10',
'HITLIST_SIZE': '1',
'ALIGNMENTS': '1',
'DESCRIPTIONS': '1',
'FORMAT_TYPE': 'HTML',
'NCBI_GI': 'on',
'SHOW_OVERVIEW': 'on',
'FORMAT_OBJECT': 'Alignment',
'CLIENT': 'web',
'SERVICE': 'plain',
'NCBI_GI': 'on',
'PAGE': 'Nucleotides',
'CMD': 'Put',
'RID': '',
'FORMAT_TYPE': 'HTML',
'PROGRAM': 'blastp',
'DATABASE': 'nr',
'QUERY': seq,
'EXPECT': '10',
'HITLIST_SIZE': '
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
EOL while scanning string literal (<string>, line 109)
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'http://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'QUERY': seq,
'DATABASE': 'nr',
'PROGRAM': 'blastp',
'FILTER': 'L',
'EXPECT': '10',
'HITLIST_SIZE': '1',
'ALIGNMENTS': '50',
'DESCRIPTIONS': '50',
'FORMAT_TYPE': 'HTML',
'CMD': 'Put'}
r = requests.post(url, data=params)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
# 4. Parse MSA
alignments = soup.find_all('pre')
# 5. Return a tuple of e score, id of top match
return alignments[0].text, alignments[1].text
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
list index out of range
bravais
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 17)
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 17)
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 17)
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 17)
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 17)
canonicalize
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
# canonicalize smiles
canonical_smiles = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_smiles.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canonical_smiles
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol))
return canonical_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
can_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
can_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return can_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
return [Chem.MolToSmiles(Chem.MolFromSmiles(smile)) for smile in smiles_list]
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
can_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
can_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return can_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
carnot_efficiency
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - (T_cold / T_hot)
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
claussius
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp((HVap / 8.314) * (1 / T1 - 1 / T2))
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 * math.exp((HVap / 8.314) * (1 / T1 - 1 / T2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp(HVap * (1/T1 - 1/T2))
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp(HVap * (1 / T1 - 1 / T2))
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp((HVap / 8.314) * (1 / T1 - 1 / T2))
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
compare_electronegativity
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
if mendeleev.element(element1).pauling_electronegativity > mendeleev.element(element2).pauling_electronegativity:
return True
else:
return False
result = True if compare_electronegativity("O","C") else FalseOutput:
'Element' object has no attribute 'pauling_electronegativity'
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = True if compare_electronegativity("O","C") else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = True if compare_electronegativity("O","C") else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = True if compare_electronegativity("O","C") else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = True if compare_electronegativity("O","C") else FalseOutput:
Success
condiff_1d
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return np.diff(x)
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return x[1:] - x[:-1]
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return np.diff(x)
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return x[1:] - x[:-1]
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
# start
return np.diff(x)
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
cubes
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(n):
sum += i * i * i
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(n):
sum += i**3
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(1, n + 1):
sum += i ** 3
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(n):
sum += i**3
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(n):
sum += i**3
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
de_broglie
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626068e-34
c = 3.0e+8
return h / (m * v * c)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62606876e-34 # Planck's constant
c = 2.99792458e8 # speed of light
return h / (m * v)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626e-34
return h / (m * v)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626068e-34
c = 3.0e+8
return h / (m * v * c)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62606896e-34
c = 299792458
return h / (m * v)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
derivative1d-ch
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
y = a*x**2 + b*x + c
dydx = 2*a*x + b
return dydx
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
# 在这里写你的代码
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
derivative_2deg
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
"""
Create a list of numbers from 0 to 10
"""
x = np.arange(0,11)
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
"""
Create a matrix of random numbers
"""
a = np.random.rand(5,10)
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append(calc.CalcDescriptors(mol))
return np.array(descriptors)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
desc_list = []
for smile in smiles_list:
m = Chem.MolFromSmiles(smile)
desc_list.append(calc.CalcDescriptors(m))
return np.array(desc_list)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
descrs = []
for smile in smiles_list:
m = Chem.MolFromSmiles(smile)
descrs.append(calc.CalcDescriptors(m))
return np.array(descrs)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
# initialize a list of descriptors
desc_list = []
# initialize a list of names
desc_names = []
# initialize a list of failed SMILES
failed_smiles = []
# initialize a list of failed SMILES
failed_smiles_index = []
# initialize a list of failed SMILES
failed_smiles_reason = []
# initialize a list of failed SMILES
failed_smiles_reason_index = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason_index = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason_index_reason = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason_index_reason_index = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason_index_reason_index_reason = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index_reason_index = []
# initialize a list of failed SMILES
failed_smiles_reason_index_reason_index_
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
name 'failed_smiles_reason_index_reason_index_' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append(calc.CalcDescriptors(mol))
return np.array(descriptors)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
dipole
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
return np.sum(coordinates * charges[:, np.newaxis], axis=0)
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
# YOUR CODE HERE
dipole_moment = np.zeros(3)
for i in range(len(coordinates)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(len(charges)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros(3)
for i in range(len(charges)):
dipole += charges[i] * coordinates[i]
return dipole
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
# start
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
unsupported operand type(s) for -: 'float' and 'NoneType'
dou
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
rdb = Descriptors.NumRadicalElectrons(mol)
return rdb
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
return Descriptors.NumRadicalElectrons(mol)
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.NumRadicalElectrons(mol)
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
return Descriptors.NumRadicalElectrons(mol)
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
return Descriptors.NumRadicalElectrons(mol)
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
eigen-ch
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# start
eigenvalues, eigenvectors = np.linalg.eig(M)
return eigenvalues, eigenvectors
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# start
eig_val, eig_vec = np.linalg.eig(M)
return eig_val, eig_vec
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# begin
eig_val, eig_vec = np.linalg.eig(M)
return eig_val, eig_vec
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
eig_val, eig_vec = np.linalg.eig(M)
return eig_val, eig_vec
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
eigen_values, eigen_vectors = np.linalg.eig(M)
return eigen_values, eigen_vectors
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
eigen
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
eigenvalues, eigenvectors = np.linalg.eig(M)
return eigenvalues, eigenvectors
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
return np.linalg.eig(M)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
return np.linalg.eig(M)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
eigenvalues, eigenvectors = np.linalg.eig(M)
return eigenvalues, eigenvectors
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
return np.linalg.eig(M)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
element_mass
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
return mendeleev.element(element_symbol).mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
element_name
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
element = mendeleev.element(element_number)
return element.symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
element = mendeleev.element(element_number)
return element.symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
element = mendeleev.element(element_number)
return element.symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
energy_of_e
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
e = 13.6 * (1 - 1 / (n ** 2))
return e
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
# start
E = -13.6 * (1 / (n ** 2))
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
must be real number, not NoneType
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
# start
h = 6.626e-34
c = 3e8
R = 1.097e7
E = -(h * c * R) / (n**2)
return E
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
return -13.6 * (1 / n ** 2)
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
# start
e = 13.6 * (1 - 1 / (n ** 2))
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
must be real number, not NoneType
find_indices
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
ca_indices = topology.select('name CA')
return ca_indices[0], ca_indices[1]
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
t = md.load(pdb_file)
ca_indices = []
for i in range(2):
ca_indices.append(t.topology.select('name CA and resid '+str(i+1)))
return ca_indices
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load_pdb(pdb_file)
topology = pdb.topology
ca_indices = [a.index for a in topology.atoms if a.name == 'CA']
return ca_indices
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
atom_indices = topology.select('name CA')
return atom_indices[0], atom_indices[1]
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
topology = pdb.topology
atom_indices = topology.select('name CA')
return atom_indices[0], atom_indices[1]
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
force_constant
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
mu = m1*m2/(m1+m2)
h = 6.626e-34
c = 3e8
wave_len_m = wave_len*1e-2
k = (h*c/wave_len_m)**2/(8*mu)
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
k = (1.0/wave_len)*(1.0/wave_len)*(m1*m2)/(m1+m2)
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
return 1.0
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
mu = m1*m2/(m1+m2)
k = (1.9872041e-23)*(1.0e-2*wave_len)**2/(mu*1.0e-23)
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
mu = m1*m2/(m1+m2)
k = mu*(wave_len*1.0e2)**2
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
fourier_1d
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
X = np.zeros(N, dtype=complex)
for k in range(N):
X[k] = np.sum(x*np.exp(-1j*2*np.pi*k*np.arange(N)/N))
return X
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
# start
N = len(x)
X = np.zeros(N, dtype=np.complex)
for k in range(N):
for n in range(N):
X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
# start
N = len(x)
X = np.zeros(N, dtype=complex)
for k in range(N):
for n in range(N):
X[k] += x[n] * np.exp(-2j * np.pi * n * k / N)
return X
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
# start
N = len(x)
X = np.zeros(N, dtype=complex)
for k in range(N):
for n in range(N):
X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
# begin
N = len(x)
X = np.zeros(N, dtype=np.complex)
for k in range(N):
for n in range(N):
X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
freezing_depression
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf*m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
genpos
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://it.iucr.org/Ac/ch4o3pr3/sgtable/' + str(gnum) + '.html'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find('table', {'class': 'matrix'})
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
generators = np.array(generators)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
'NoneType' object has no attribute 'find_all'
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-gen-matrices?gnum=" + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
table = soup.find_all('table')[0]
rows = table.find_all('tr')
matrices = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
matrices.append([ele for ele in cols if ele])
return matrices
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-getgen?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
table = soup.find('pre')
table = table.text.split('\n')
table = table[1:-1]
table = [i.split() for i in table]
return table
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum=" + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
table = soup.find_all('table')[0]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
generators = generators[1:]
for i in range(len(generators)):
generators[i][0] = int(generators[i][0])
generators[i][1] = generators[i][1].replace('(', '')
generators[i][1] = generators[i][1].replace(')', '')
generators[i][1] = generators[i][1].replace(' ', '')
generators[i][1] = generators[i][1].split(',')
generators[i][1] = [int(x) for x in generators[i][1]]
generators[i][2] = generators[i][2].replace('(', '')
generators[i][2] = generators[i][2].replace(')', '')
generators[i][2] = generators[i][2].replace(' ', '')
generators[i][2] = generators[i][2].split(',')
generators[i][2] = [int(x) for x in generators[i][2]]
generators[i][3] = generators[i][3].replace('(', '')
generators[i][3] = generators[i][3].replace(')', '')
generators[i][3] = generators[i][3].replace(' ', '')
generators[i][3] = generators[i][3].split(',')
generators[i][3] = [int(x) for x in generators[i][3]]
generators[i][4] = generators[i][4].replace('(', '')
generators[i][4] = generators[i][4].replace(')', '')
generators[i][4] = generators[i][4].replace(' ', '')
generators[i][4] = generators[i][4].split(',')
generators[i][4] = [int(x) for x in generators[i][4]]
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-gen-matrices?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
table = soup.find_all('table')[0]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
generators = np.array(generators)
generators = generators[1:,1:]
generators = generators.astype(float)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
heating_water
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * 4.184 * (T2 - T1)
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
Q = n * 4.184 * (T2 - T1)
return Q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * (T2 - T1) * 4.184
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * 4.184 * (T2 - T1)
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * (T2 - T1) * 4.184
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
hydrophobic_res
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# load pdb file
traj = md.load(pdb_filename)
# get residues
residues = traj.topology.residues
# get hydrophobic residues
hydrophobic_residues = [residue.index for residue in residues if residue.is_hydrophobic]
# return
return hydrophobic_residues
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# Load pdb file
pdb = md.load_pdb(pdb_filename)
# Get list of all residues
residues = pdb.topology.residues
# Get list of hydrophobic residues
hydrophobic_residues = [residue.index for residue in residues if residue.is_hydrophobic]
# Return list of hydrophobic residues
return hydrophobic_residues
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# Load PDB file
pdb = md.load_pdb(pdb_filename)
# Get list of hydrophobic residues
hydrophobic_residues = []
for residue in pdb.topology.residues:
if residue.is_water:
continue
if residue.name in ['ALA', 'VAL', 'LEU', 'ILE', 'MET', 'PHE', 'TRP', 'PRO', 'CYS']:
hydrophobic_residues.append(residue.index)
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# Load PDB file
pdb_file = md.load_pdb(pdb_filename)
# Get list of hydrophobic residues
hydrophobic_residues = [residue.index for residue in pdb_file.topology.residues if residue.is_hydrophobic]
# Return list of hydrophobic residues
return hydrophobic_residues
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# Load PDB file
pdb_file = md.load_pdb(pdb_filename)
# Get list of hydrophobic residues
hydrophobic_residues = [residue.index for residue in pdb_file.topology.residues if residue.is_hydrophobic]
# Return list of hydrophobic residues
return hydrophobic_residues
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
ideal_gas
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # L atm / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm L / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm L / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # L atm / mol K
return n*R*T/V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 #L atm / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
integral
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
return a*d**3/4 + b*d**2/3 + c*d
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
return a*d**3/4 + b*d**2/3 + c*d
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
return (a/4)*d**4 + (b/3)*d**3 + (c/2)*d**2 + d
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
trap
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
s = 0.5*f(a) + 0.5*f(b)
for i in range(1,n):
s += f(a + i*h)
return h*s
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
s = 0.5*(f(a) + f(b))
for i in range(1,n):
s += f(a + i*h)
return h*s
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
x = np.linspace(a,b,n+1)
y = f(x)
return h*(0.5*y[0] + 0.5*y[n] + np.sum(y[1:n]))
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
s = 0.5 * (f(a) + f(b))
for i in range(1, n):
s = s + f(a + i * h)
return s * h
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
x = np.linspace(a, b, n+1)
y = f(x)
return h*(0.5*y[0] + 0.5*y[-1] + np.sum(y[1:-1]))
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
invert_matrix
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# start
A_inv = np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# compute the inverse of A
A_inv = np.linalg.inv(A)
return A_inv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# your code here
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
return np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# start
return np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
iupac2smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
return Chem.MolToSmiles(mol)
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
return Chem.MolToSmiles(mol)
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
m = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
kld
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
kl_loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
langevin_dynamics
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
# TODO: implement the Langevin dynamics
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
expected an indented block (<string>, line 29)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
x_traj[i+1] = x_traj[i] + v_traj[i]*dt
v_traj[i+1] = v_traj[i] + (F(x_traj[i])/m - gamma*v_traj[i] + np.sqrt(2*gamma*T/m)*np.random.normal())*dt
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
x_traj[i+1] = x_traj[i] + dt*v_traj[i]
v_traj[i+1] = v_traj[i] + dt*(F(x_traj[i])/m - gamma*v_traj[i] + np.sqrt(2*gamma*T/m)*np.random.normal())
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
# TODO: implement the Langevin dynamics
# Hint: you can use np.random.normal to sample from a normal distribution
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
expected an indented block (<string>, line 30)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x = x0
v = v0
for i in range(n_steps):
x_traj[i] = x
v_traj[i] = v
v = v + (F(x) - gamma*v + np.sqrt(2*gamma*T/m)*np.random.randn())*dt/m
x = x + v*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
weighted-least-squares
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
return np.linalg.inv(x.T.dot(np.diag(w).dot(x))).dot(x.T).dot(np.diag(w).dot(y))
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
return np.linalg.inv(x.T.dot(w).dot(x)).dot(x.T).dot(w).dot(y)
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,) and (100,3) not aligned: 3 (dim 0) != 100 (dim 0)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
# YOUR CODE HERE
#raise NotImplementedError()
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
# start
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
return np.linalg.inv(x.T*w*x)*x.T*w*y
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
return np.linalg.inv(x.T @ w @ x) @ x.T @ w @ y
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 100 is different from 3)
lipinski_rule_of_five
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
hbd = rdMolDescriptors.CalcNumHBD(mol)
hba = rdMolDescriptors.CalcNumHBA(mol)
mw = Descriptors.MolWt(mol)
logp = Crippen.MolLogP(mol)
if hbd <= 5 and hba <= 10 and mw < 500 and logp < 5:
return True
else:
return False
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
m = Chem.MolFromSmiles(smiles)
if m is None:
return False
else:
if rdMolDescriptors.CalcNumHBD(m) > 5:
return False
if rdMolDescriptors.CalcNumHBA(m) > 10:
return False
if Descriptors.MolWt(m) > 500:
return False
if Crippen.MolLogP(m) > 5:
return False
else:
return True
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
m = Chem.MolFromSmiles(smiles)
if m is None:
return False
else:
hbd = rdMolDescriptors.CalcNumHBD(m)
hba = rdMolDescriptors.CalcNumHBA(m)
logp = Crippen.MolLogP(m)
mol_weight = Descriptors.MolWt(m)
if hbd <= 5 and hba <= 10 and mol_weight <= 500 and logp <= 5:
return True
else:
return False
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
#print(mol)
#print(smiles)
#print(Chem.MolToSmiles(mol))
#print(Chem.MolToMolBlock(mol))
#print(Chem.MolToPDBBlock(mol))
#print(Chem.MolToInchi(mol))
#print(Chem.MolToInchiKey(mol))
#print(Chem.MolToMolBlock(mol))
#print(Chem.MolToMolFile(mol))
#print(Chem.MolToSmarts(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem.MolToTPLFile(mol))
#print(Chem
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
hbd = rdMolDescriptors.CalcNumHBD(mol)
hba = rdMolDescriptors.CalcNumHBA(mol)
mw = Descriptors.MolWt(mol)
logp = Crippen.MolLogP(mol)
if hbd <= 5 and hba <= 10 and mw < 500 and logp < 5:
return True
else:
return False
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
mape
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
return np.mean(np.abs((y-y_hat)/y))
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
return np.mean(np.abs((y - y_hat) / y)) * 100
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
mape = np.mean(np.abs((y - y_hat) / y)) * 100
return mape
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
# start
mape = np.mean(np.abs((y - y_hat) / y)) * 100
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
# start
mape = 0
for i in range(len(y)):
mape += abs((y_hat[i]-y[i])/y[i])
mape = mape/len(y)
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
mapping_operator
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# Get the number of beads
n_beads = len(beads_mappings)
# Get the number of atoms
n_atoms = molecule.n_atoms
# Create the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms))
# Loop over the beads
for bead_index in range(n_beads):
# Get the bead
bead = beads_mappings[bead_index]
# Get the masses
masses = bead.masses
# Get the number of atoms in the bead
n_bead_atoms = bead.n_atoms
# Get the total mass of the bead
total_mass = masses.sum()
# Set the mapping matrix
mapping_matrix[bead_index, bead.indices] = masses / total_mass
# Return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'masses'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# get the number of beads
n_beads = len(beads_mappings)
# get the number of atoms
n_atoms = molecule.n_atoms
# create the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms))
# loop over the beads
for bead_index, bead_selection in enumerate(beads_mappings):
# get the masses of the atoms in the bead
masses = molecule.select_atoms(bead_selection).masses
# get the number of atoms in the bead
n_atoms_in_bead = len(masses)
# get the total mass of the bead
total_mass = masses.sum()
# loop over the atoms in the bead
for atom_index in range(n_atoms_in_bead):
# get the mass of the atom
mass = masses[atom_index]
# set the mapping matrix
mapping_matrix[bead_index, atom_index] = mass / total_mass
# return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'replace'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# Get the number of beads
n_beads = len(beads_mappings)
# Get the number of atoms
n_atoms = molecule.n_atoms
# Create the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms))
# Loop over the beads
for bead_index in range(n_beads):
# Get the bead
bead = beads_mappings[bead_index]
# Get the atoms
atoms = molecule.select_atoms(bead)
# Get the number of atoms
n_atoms_bead = atoms.n_atoms
# Get the masses
masses = atoms.masses
# Get the total mass
total_mass = masses.sum()
# Get the mass-mass weighted mapping
mass_mass_mapping = masses / total_mass
# Store the mapping
mapping_matrix[bead_index, atoms.indices] = mass_mass_mapping
# Return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'replace'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# Initialize the mapping matrix
mapping_matrix = np.zeros((molecule.n_atoms, molecule.n_atoms))
# Loop over all beads
for bead_index, bead_selection in enumerate(beads_mappings):
# Get the indices of the atoms in the bead
bead_indices = bead_selection.indices
# Get the masses of the atoms in the bead
bead_masses = molecule.masses[bead_indices]
# Get the total mass of the bead
bead_mass = np.sum(bead_masses)
# Get the mass-mass weighted mapping matrix for the bead
bead_mapping_matrix = np.outer(bead_masses, bead_masses) / bead_mass
# Add the bead mapping matrix to the total mapping matrix
mapping_matrix[np.ix_(bead_indices, bead_indices)] += bead_mapping_matrix
# Return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'indices'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# get the number of beads
n_beads = len(beads_mappings)
# get the number of atoms
n_atoms = molecule.n_atoms
# initialize the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms))
# loop over the beads
for bead_index, bead_mapping in enumerate(beads_mappings):
# get the atom indices
atom_indices = bead_mapping.indices
# get the atom masses
atom_masses = bead_mapping.masses
# get the total mass
total_mass = np.sum(atom_masses)
# loop over the atoms
for atom_index, atom_mass in zip(atom_indices, atom_masses):
# set the mapping matrix
mapping_matrix[bead_index, atom_index] = atom_mass / total_mass
# return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'indices'
matpow
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.eye(x.shape[0])
elif n == 1:
return x
elif n%2 == 0:
return matpow(x.dot(x),n/2)
else:
return x.dot(matpow(x.dot(x),(n-1)/2))
"""
Compute matrix power
"""
b = matpow(a,2)
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
shapes (5,10) and (5,10) not aligned: 10 (dim 1) != 5 (dim 0)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.identity(x.shape[0])
elif n == 1:
return x
elif n % 2 == 0:
return matpow(np.dot(x,x), n/2)
else:
return np.dot(x, matpow(x, n-1))
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.identity(x.shape[0])
elif n == 1:
return x
elif n % 2 == 0:
return matpow(x.dot(x), n/2)
else:
return x.dot(matpow(x, n-1))
"""
Compute matrix power
"""
b = matpow(a,3)
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
shapes (5,10) and (5,10) not aligned: 10 (dim 1) != 5 (dim 0)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.identity(x.shape[0])
elif n == 1:
return x
elif n % 2 == 0:
return matpow(x.dot(x),n/2)
else:
return x.dot(matpow(x.dot(x),(n-1)/2))
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.eye(x.shape[0])
elif n == 1:
return x
elif n % 2 == 0:
return matpow(x.dot(x), n/2)
else:
return x.dot(matpow(x, n-1))
"""
Compute the matrix x raised to the power n
"""
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
n = 3
print(matpow(x,n))
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
matrix_factorial
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
# start
return np.prod(np.arange(1,n+1))
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
# start
return np.array([np.math.factorial(i) for i in n])
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
# start
return np.prod(np.arange(1,n+1))
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
return np.prod(np.arange(1,n+1))
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
return np.prod(np.arange(1,n+1))
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
max-boltz
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23 # Boltzmann constant in J/K
return math.sqrt(3*k*T/M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806503e-23 # Boltzmann constant
return math.sqrt(k * T / M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.38064852e-23 # Boltzmann constant in m^2 kg s^-2 K^-1
return math.sqrt(k*T/M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806503e-23
return math.sqrt(3 * k * T / M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806503e-23 # Boltzmann constant in SI units
return math.sqrt(3*k*T/M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
michaelis
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
mol_charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return rdMolDescriptors.CalcFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
module 'rdkit.Chem.rdMolDescriptors' has no attribute 'CalcFormalCharge'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
net_charge
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
# start
net_charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
net_charge += 1
elif aa == 'D' or aa == 'E':
net_charge -= 1
return net_charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
# start
net_charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
net_charge += 1
elif aa == 'D' or aa == 'E':
net_charge -= 1
return net_charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
net_charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
net_charge += 1
elif aa == 'D' or aa == 'E':
net_charge -= 1
return net_charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
solve_ode
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
y = np.zeros((len(t), len(y0)))
y[0] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = h * fn(t[i], y[i])
k2 = h * fn(t[i] + h/4, y[i] + k1/4)
k3 = h * fn(t[i] + 3*h/8, y[i] + 3*k1/32 + 9*k2/32)
k4 = h * fn(t[i] + 12*h/13, y[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h * fn(t[i] + h, y[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h * fn(t[i] + h/2, y[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1] = y[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
# Initialize
y = np.zeros((len(t), len(y0)))
y[0,:] = y0
h = t[1] - t[0]
# Loop
for i in range(len(t)-1):
k1 = h*fn(t[i], y[i,:])
k2 = h*fn(t[i] + h/4, y[i,:] + k1/4)
k3 = h*fn(t[i] + 3*h/8, y[i,:] + 3*k1/32 + 9*k2/32)
k4 = h*fn(t[i] + 12*h/13, y[i,:] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h*fn(t[i] + h, y[i,:] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h*fn(t[i] + h/2, y[i,:] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1,:] = y[i,:] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
# Initialize
y = np.zeros((len(t),len(y0)))
y[0,:] = y0
h = t[1]-t[0]
# Loop
for i in range(len(t)-1):
k1 = fn(t[i], y[i,:])
k2 = fn(t[i]+h/4, y[i,:]+h/4*k1)
k3 = fn(t[i]+3*h/8, y[i,:]+3*h/32*k1+9*h/32*k2)
k4 = fn(t[i]+12*h/13, y[i,:]+1932*h/2197*k1-7200*h/2197*k2+7296*h/2197*k3)
k5 = fn(t[i]+h, y[i,:]+439*h/216*k1-8*h*k2+3680*h/513*k3-845*h/4104*k4)
k6 = fn(t[i]+h/2, y[i,:]-8*h/27*k1+2*h*k2-3544*h/2565*k3+1859*h/4104*k4-11*h/40*k5)
y[i+1,:] = y[i,:]+h/6*(25*k1/216+1408*k3/2565+2197*k4/4104-k5/5)
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
# start
n = len(t)
y = np.zeros((n, len(y0)))
y[0] = y0
for i in range(n-1):
h = t[i+1] - t[i]
k1 = h*fn(t[i], y[i])
k2 = h*fn(t[i] + h/4, y[i] + k1/4)
k3 = h*fn(t[i] + 3*h/8, y[i] + 3*k1/32 + 9*k2/32)
k4 = h*fn(t[i] + 12*h/13, y[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h*fn(t[i] + h, y[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h*fn(t[i] + h/2, y[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1] = y[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
y = np.zeros((len(t), len(y0)))
y[0] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = h * fn(t[i], y[i])
k2 = h * fn(t[i] + h/4, y[i] + k1/4)
k3 = h * fn(t[i] + 3*h/8, y[i] + 3*k1/32 + 9*k2/32)
k4 = h * fn(t[i] + 12*h/13, y[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h * fn(t[i] + h, y[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h * fn(t[i] + h/2, y[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1] = y[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
ohe
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# start
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
#raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
#raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
# raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
#raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
osmotic_pressure
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi / (R * T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi / (R * T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi / (R * T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi / (R * T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi / (R * T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
pair_wise
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# Load the pdb file
traj = md.load(pdb_file)
# Select only the alpha carbons
alpha_carbons = traj.topology.select('name CA')
# Calculate the number of unique alpha carbon pairs
num_pairs = len(alpha_carbons) * (len(alpha_carbons) - 1) / 2
# Calculate the distances between each alpha carbon pair
distances = md.compute_distances(traj, alpha_carbons, alpha_carbons)
# Return the distances between each alpha carbon pair
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# 1
pdb = md.load(pdb_file)
# 2
pdb_alpha = pdb.atom_slice(pdb.top.select('name CA'))
# 3
n_alpha = pdb_alpha.n_atoms
# 4
return md.compute_distances(pdb_alpha, [[i, j] for i in range(n_alpha) for j in range(i)])
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# Load the pdb file
traj = md.load(pdb_file)
# Select only the alpha carbons
alpha_carbons = traj.topology.select('name CA')
# Calculate the number of unique alpha carbon pairs
num_pairs = len(alpha_carbons) * (len(alpha_carbons) - 1) / 2
# Calculate the distances between each alpha carbon pair
distances = md.compute_distances(traj, alpha_carbons, alpha_carbons)
# Return the distances between each alpha carbon pair
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# 1
pdb = md.load_pdb(pdb_file)
# 2
pdb_alpha = pdb.atom_slice(pdb.top.select('name CA'))
# 3
n_pairs = pdb_alpha.n_atoms * (pdb_alpha.n_atoms - 1) / 2
# 4
return md.compute_distances(pdb_alpha, [[i, j] for i in range(pdb_alpha.n_atoms) for j in range(i)])
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# 1
traj = md.load(pdb_file)
# 2
alpha_carbons = traj.topology.select('name CA')
# 3
alpha_pairs = list(itertools.combinations(alpha_carbons, 2))
# 4
distances = md.compute_distances(traj, alpha_pairs)
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
pi
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
return 4.0*np.sum(r<1)/nsamples
"""
Create a function that returns the value of pi by monte carlo sampling
"""
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
nhits = 0
for i in range(nsamples):
x, y = np.random.uniform(-1.0, 1.0, 2)
if x ** 2 + y ** 2 < 1.0:
nhits += 1
return 4 * nhits / float(nsamples)
"""
Create a function that returns the value of pi by monte carlo sampling
"""
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
return 4*np.sum(r<1)/nsamples
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
# create matrix of random numbers
x = np.random.rand(nsamples,2)
# compute the distance from the origin
r = np.sqrt(x[:,0]**2 + x[:,1]**2)
# count the number of points inside the unit circle
n = np.sum(r < 1)
# return the value of pi
return 4.0*n/nsamples
"""
Compute pi using monte carlo sampling
"""
print(pi(10000))
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
return 4*np.sum(r<1)/nsamples
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
pib_1d
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n**2 * math.pi**2 * hbar**2) / (2 * m * L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
# start
energy = (n**2 * math.pi**2 * hbar**2)/(2 * m * L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
unsupported operand type(s) for -: 'float' and 'NoneType'
pred_interval
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return np.ceil(np.log(1-pred_level)/np.log(1-p))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return np.ceil(np.log(1 - pred_level) / np.log(1 - p))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return int(np.ceil(np.log(1-pred_level)/np.log(1-p)))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return int(np.ceil(np.log(1-pred_level)/np.log(1-p)))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return np.ceil(np.log(1 - pred_level) / np.log(1 - p))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
pubchem
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
# PubChem REST API
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT" % smiles
response = requests.get(url)
cids = response.text.split()
# PubChem REST API
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT" % ",".join(cids)
response = requests.get(url)
return set(response.text.split())
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
# create a PubChem REST API query
query = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT?cids_type=similarity&Threshold=80" % smiles
# send the query
response = requests.get(query)
# parse the response
cids = response.text.split()
# create a PubChem REST API query
query = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT" % ",".join(cids)
# send the query
response = requests.get(query)
# parse the response
return set(response.text.split())
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
# The PubChem REST API requires the SMILES string to be URL encoded.
smiles = urllib.quote(smiles)
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
similarity = 0.8
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
# The PubChem REST API requires the similarity to be a floating point number between 0 and 1.
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
name 'urllib' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
# PubChem REST API
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles
# get the response
response = requests.get(url)
# convert the response to a string
response = response.text
# split the response into a list of CIDs
cids = response.split()
# create a list to store the SMILES strings
similar_molecules = []
# loop through the CIDs
for cid in cids:
# PubChem REST API
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT' % cid
# get the response
response = requests.get(url)
# convert the response to a string
response = response.text
# append the SMILES string to the list
similar_molecules.append(response)
# return the list of SMILES strings
return similar_molecules
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles
response = requests.get(url)
cids = response.text.split()
cids = ','.join(cids)
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT' % cids
response = requests.get(url)
return set(response.text.split())
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
pyscf_energy
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom, basis=basis)
mf = pyscf.scf.RHF(mol)
mf.scf()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mf = pyscf.scf.RHF(mol)
mf.scf()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mf = pyscf.scf.RHF(mol)
mf.kernel()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
qed
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.MolLogP(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
quantile
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.quantile(a, q)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.percentile(a, q * 100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
return np.percentile(a, q*100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.percentile(a, q * 100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.quantile(a, q)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
Success
random_walk
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*np.random.choice([-1,1])
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Timeout
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(np.random.randint(2)*2-1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(2*np.random.randint(2)-1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N+1)
x[0] = x0
for i in range(N):
x[i+1] = x[i] + a*(2*np.random.randint(2)-1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
expected x and y to have same length
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
for i in range(N):
x[i] = x0 + a*(2*np.random.randint(2)-1)
x0 = x[i]
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
rank
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, S, V = np.linalg.svd(M)
return np.sum(S > 1e-10)
"""
Create matrix of ones
"""
a = np.ones((5,10))
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, S, V = np.linalg.svd(M)
return len(S)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
# start
U, s, V = np.linalg.svd(M)
return np.sum(s > 1e-10)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
return np.sum(s > 1e-10)
"""
Create matrix of ones
"""
a = np.ones((5,10))
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
return np.sum(s > 1e-10)
"""
Create matrix of ones
"""
a = np.ones((5,10))
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
remove-water
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
rms_velocity
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
rmse
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
rog
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
return md.compute_rg(traj)
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load the pdb file
traj = md.load(pdb_file)
# Calculate the radius of gyration
rgyr = md.compute_rg(traj)
# Return the radius of gyration
return rgyr
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load the pdb file
traj = md.load(pdb_file)
# Calculate the radius of gyration
rgyr = md.compute_rg(traj)
# Return the radius of gyration
return rgyr
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
protein_atoms = traj.topology.select("protein")
protein_traj = traj.atom_slice(protein_atoms)
protein_radius_of_gyration = md.compute_rg(protein_traj)
return protein_radius_of_gyration
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load the pdb file
traj = md.load(pdb_file)
# Calculate the radius of gyration
radius_of_gyration = md.compute_rg(traj)
# Return the radius of gyration
return radius_of_gyration
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
sasa
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load the pdb
traj = md.load(pdb_file)
# Calculate the sasa
sasa = md.shrake_rupley(traj)
# Return the sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
topology = traj.topology
residues = topology.residues
sasa = md.shrake_rupley(traj, mode='residue')
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load the pdb
traj = md.load(pdb_file)
# Calculate the sasa
sasa = md.shrake_rupley(traj, mode='residue')
# Return the sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load the pdb
traj = md.load(pdb_file)
# Calculate the sasa
sasa = md.shrake_rupley(traj)
# Return the sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load the pdb file
traj = md.load(pdb_file)
# Calculate the sasa
sasa = md.shrake_rupley(traj)
# Return the sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
scaffold
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
engine = Scaffold.ScaffoldGenerator()
scaffold = engine.GetScaffoldForMol(mol)
return Chem.MolToSmiles(scaffold, isomericSmiles=True)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
name 'Scaffold' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
engine = Scaffold.ScaffoldGenerator()
scaffold = engine.GetScaffoldForMol(mol)
return Chem.MolToSmiles(scaffold, isomericSmiles=True)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
name 'Scaffold' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.RemoveHs(mol),True))
return scaffold
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
engine = MurckoScaffold.MurckoScaffoldSmilesGenerator()
scaffold = engine.GetScaffoldForMol(mol)
return scaffold
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
name 'MurckoScaffold' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
engine = Scaffold.ScaffoldGenerator()
scaffold = engine.GetScaffoldForMol(mol)
return Chem.MolToSmiles(scaffold, isomericSmiles=True)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
name 'Scaffold' is not defined
seq-align
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln_seq1, aln_seq2, score, begin, end = top_aln
return aln_seq1, aln_seq2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln_seq1, aln_seq2, score, begin, end = top_aln
return aln_seq1, aln_seq2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
return alns
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln_seq1, aln_seq2, score, begin, end = top_aln
return aln_seq1, aln_seq2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln_seq1, aln_seq2, score, begin, end = top_aln
return aln_seq1, aln_seq2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
seq-trans
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
# create a sequence object
seq = Seq(gene_seq)
# translate the sequence
protein = seq.translate()
return protein
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
# create a sequence object
seq = Seq(gene_seq)
# translate the sequence
protein = seq.translate()
return protein
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
sequence
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.geomspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.geomspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.geomspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
# start
return np.linspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
r = (e/s)**(1/(l-1))
return s*r**np.arange(l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
sle
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create symbols
x = sympy.symbols('x:%d' % len(eqns))
# create a matrix
A = sympy.Matrix(eqns).T
# create a vector
b = sympy.Matrix(sympy.symbols('b:%d' % len(eqns)))
# solve the system of linear equations
sol = A.LUsolve(b)
# return the solution
return sol
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create a list of variables
x = sympy.symbols('x:%d' % len(eqns))
# create a list of equations
eqns = [sympy.sympify(eq) for eq in eqns]
# solve the system of equations
sol = sympy.solve(eqns, x)
# return the solution
return sol
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create a list of symbols
symbols = []
for eqn in eqns:
for symbol in eqn.split('+'):
if symbol.find('=') == -1:
if symbol.find('-') == -1:
if symbol.find('*') == -1:
if symbol.find('/') == -1:
if symbol.find('^') == -1:
if symbol.find('(') == -1:
if symbol.find(')') == -1:
if symbol.find(' ') == -1:
if symbol not in symbols:
symbols.append(symbol)
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
'NoneType' object has no attribute 'values'
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create a list of symbols
symbols = []
for i in range(len(eqns)):
symbols.append(sympy.Symbol('x_'+str(i)))
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
'NoneType' object has no attribute 'values'
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create a list of variables
vars = []
for eqn in eqns:
for var in eqn.split('+'):
var = var.split('-')[-1]
var = var.split('=')[0]
var = var.strip()
if var not in vars:
vars.append(var)
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
'NoneType' object has no attribute 'values'
spectral_r
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eigenvalues = np.linalg.eigvals(a)
return np.max(np.abs(eigenvalues))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eigenvalues = np.linalg.eigvals(a)
spectral_r = np.max(np.abs(eigenvalues))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eigenvalues = np.linalg.eigvals(a)
spectral_r = np.max(np.abs(eigenvalues))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eig_vals, eig_vecs = np.linalg.eig(a)
return np.max(np.abs(eig_vals))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
find_peaks
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:,1], height=0)
# Sort the peaks by height
peak_heights = abs_spectrum[peaks,1]
sorted_peak_indices = np.argsort(peak_heights)[::-1]
# Return the highest `npeaks` peaks
return abs_spectrum[peaks[sorted_peak_indices[:npeaks]],0]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0.1)
# Sort the peaks by height
peak_heights = abs_spectrum[peaks, 1]
sorted_indices = np.argsort(peak_heights)
# Return the wavenumbers of the highest peaks
return abs_spectrum[peaks[sorted_indices[-npeaks:]], 0]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0)
# Sort the peaks by height
peaks = peaks[np.argsort(abs_spectrum[peaks, 1])][::-1]
# Return the wavenumbers of the highest `npeaks` peaks
return abs_spectrum[peaks[:npeaks], 0]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:,1], height=0.1)
# Sort the peaks by height
peaks = peaks[np.argsort(abs_spectrum[peaks,1])][::-1]
# Return the first `npeaks` peaks
return abs_spectrum[peaks[:npeaks],0]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:,1], height=0.1)
# Sort the peaks by height
peak_heights = abs_spectrum[peaks, 1]
sorted_peak_indices = np.argsort(peak_heights)[::-1]
# Return the wavenumbers of the highest peaks
return abs_spectrum[peaks[sorted_peak_indices[:npeaks]], 0]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
speed_of_sound
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
substructure
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a query molecule from the smiles string
query = Chem.MolFromSmiles(smiles)
# create a list to store the indices of the matching molecules
matches = []
# loop through the molecules in mol_list
for i in range(len(mol_list)):
# if the query is a substructure of the molecule
if mol_list[i].HasSubstructMatch(query):
# add the index to the matches list
matches.append(i)
# return the matches list
return matches
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a mol object from the smiles string
query_mol = Chem.MolFromSmiles(smiles)
# create a list to store the indices of the entries that contain the substructure
indices = []
# loop through mol_list
for i in range(len(mol_list)):
# check if the mol object contains the substructure
if mol_list[i].HasSubstructMatch(query_mol):
# if it does, add the index to the list
indices.append(i)
# return the list of indices
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a mol object from the smiles string
mol = Chem.MolFromSmiles(smiles)
# create a list of indices that contain the substructure
indices = [i for i, x in enumerate(mol_list) if x.HasSubstructMatch(mol)]
# return the list of indices
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a query molecule from the smiles string
query_mol = Chem.MolFromSmiles(smiles)
# create a list to store the indices of the matching molecules
match_list = []
# loop through mol_list
for i in range(len(mol_list)):
# if the query molecule is a substructure of mol_list[i]
if mol_list[i].HasSubstructMatch(query_mol):
# add the index to match_list
match_list.append(i)
# return the list of indices
return match_list
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a molecule from the smiles string
mol = Chem.MolFromSmiles(smiles)
# create a list to store the indices of the molecules that contain the substructure
indices = []
# loop through the molecules in mol_list
for i in range(len(mol_list)):
# if the molecule contains the substructure, add the index to the list
if mol_list[i].HasSubstructMatch(mol):
indices.append(i)
# return the list of indices
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
tanimoto
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(i, len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
tanimoto_matrix[j, i] = tanimoto_matrix[i, j]
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize the matrix
tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))
# generate the fingerprints
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
# calculate the Tanimoto similarity
for i, fp1 in enumerate(fps):
for j, fp2 in enumerate(fps):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fp1, fp2)
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize empty matrix
tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))
# generate ECFP4 fingerprints
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
# calculate Tanimoto similarity
for i, fp1 in enumerate(fps):
for j, fp2 in enumerate(fps):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fp1, fp2)
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize empty matrix
tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))
# generate ECFP4 fingerprints
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
# calculate pairwise Tanimoto similarity
for i in range(len(smiles_list)):
for j in range(len(smiles_list)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# generate Morgan fingerprints
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
# generate similarity matrix
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i,j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
unbdistance
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# Get the residue number of the ligand
lig_res = traj.topology.select('resname '+lig_str)
# Get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_res))
# Get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(traj.topology.select('protein')))
# Compute the distance between the two centers of mass
distance = md.compute_distances(traj,lig_com,prot_com)
return distance
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the indices of the ligand
lig_ind = traj.topology.select('resname '+lig_str)
# get the indices of the protein
prot_ind = traj.topology.select('protein')
# get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# get the distance between the two center of mass
dist = md.compute_distances(traj,[lig_com,prot_com],periodic=False)
# return the distance
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the indices of the ligand
lig_ind = traj.topology.select('resname ' + lig_str)
# get the indices of the protein
prot_ind = traj.topology.select('protein')
# get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# get the distance between the two
dist = md.compute_distances(traj,lig_com,prot_com)
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the index of the ligand
lig_ind = traj.topology.select('resname '+lig_str)
# get the index of the protein
prot_ind = traj.topology.select('protein')
# get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# get the distance between the two centers of mass
dist = md.compute_distances(traj,lig_com,prot_com)
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the protein
protein = traj.topology.select('protein')
# get the ligand
ligand = traj.topology.select('resname ' + lig_str)
# get the center of mass of protein
com_protein = md.compute_center_of_mass(traj.atom_slice(protein))
# get the center of mass of ligand
com_ligand = md.compute_center_of_mass(traj.atom_slice(ligand))
# get the distance between the two
distance = md.compute_distances(traj,com_protein,com_ligand)
# return the distance
return distance
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
T = 0.2
Prompt Override = insert
| Test | Run 0 | Run 1 | Run 2 | Run 3 | Run 4 |
|---|---|---|---|---|---|
| aa_polarity | Fail | Fail | Fail | Fail | Fail |
| adiabatic_expansion | Fail | Fail | Fail | Fail | Fail |
| alignment | Fail | Fail | Fail | Fail | Fail |
| angle | Pass | Pass | Pass | Pass | Pass |
| aromatic_aa | Fail | Fail | Fail | Fail | Fail |
| arrhenius | Fail | Fail | Fail | Fail | Fail |
| bimolecular | Fail | Fail | Pass | Pass | Fail |
| bb_rad | Fail | Fail | Fail | Fail | Fail |
| blast | Fail | Fail | Fail | Fail | Fail |
| bravais | Fail | Fail | Fail | Fail | Fail |
| canonicalize | Pass | Pass | Pass | Pass | Pass |
| carnot_efficiency | Fail | Fail | Fail | Fail | Fail |
| claussius | Fail | Fail | Fail | Fail | Fail |
| compare_electronegativity | Fail | Fail | Fail | Fail | Fail |
| condiff_1d | Pass | Pass | Pass | Pass | Pass |
| cubes | Fail | Fail | Fail | Fail | Fail |
| de_broglie | Pass | Fail | Fail | Fail | Fail |
| derivative1d-ch | Fail | Fail | Fail | Fail | Fail |
| derivative_2deg | Fail | Fail | Fail | Fail | Fail |
| descriptors | Fail | Fail | Fail | Fail | Fail |
| dipole | Fail | Fail | Fail | Fail | Fail |
| dou | Fail | Fail | Fail | Fail | Fail |
| eigen-ch | Fail | Fail | Fail | Fail | Fail |
| eigen | Pass | Fail | Fail | Fail | Fail |
| element_mass | Fail | Fail | Fail | Fail | Fail |
| element_name | Fail | Fail | Fail | Fail | Fail |
| energy_of_e | Fail | Fail | Fail | Fail | Fail |
| find_indices | Fail | Fail | Fail | Fail | Fail |
| force_constant | Fail | Fail | Fail | Fail | Fail |
| fourier_1d | Fail | Fail | Fail | Fail | Fail |
| freezing_depression | Fail | Fail | Fail | Fail | Fail |
| genpos | Fail | Fail | Fail | Fail | Fail |
| heating_water | Fail | Fail | Pass | Fail | Fail |
| hydrophobic_res | Fail | Fail | Fail | Fail | Fail |
| ideal_gas | Fail | Fail | Fail | Fail | Fail |
| integral | Fail | Fail | Fail | Fail | Fail |
| trap | Fail | Fail | Fail | Fail | Fail |
| invert_matrix | Fail | Fail | Fail | Fail | Fail |
| iupac2smiles | Fail | Fail | Fail | Fail | Fail |
| kld | Fail | Fail | Fail | Fail | Fail |
| langevin_dynamics | Fail | Fail | Fail | Fail | Fail |
| weighted-least-squares | Fail | Fail | Fail | Fail | Fail |
| lipinski_rule_of_five | Fail | Fail | Fail | Fail | Fail |
| mape | Fail | Fail | Fail | Fail | Fail |
| mapping_operator | Fail | Fail | Fail | Fail | Fail |
| matpow | Fail | Fail | Fail | Fail | Fail |
| matrix_factorial | Fail | Fail | Fail | Fail | Fail |
| max-boltz | Fail | Fail | Fail | Fail | Fail |
| michaelis | Fail | Fail | Fail | Fail | Fail |
| mol_charge | Pass | Pass | Pass | Pass | Pass |
| net_charge | Fail | Fail | Fail | Fail | Fail |
| solve_ode | Fail | Fail | Fail | Fail | Fail |
| ohe | Fail | Fail | Fail | Fail | Fail |
| osmotic_pressure | Fail | Fail | Fail | Fail | Fail |
| pair_wise | Fail | Fail | Fail | Fail | Fail |
| pi | Fail | Fail | Fail | Fail | Fail |
| pib_1d | Fail | Fail | Fail | Fail | Fail |
| pred_interval | Fail | Fail | Fail | Fail | Fail |
| pubchem | Fail | Fail | Fail | Fail | Fail |
| pyscf_energy | Fail | Fail | Fail | Fail | Fail |
| qed | Fail | Fail | Fail | Fail | Fail |
| quantile | Fail | Fail | Fail | Fail | Fail |
| random_walk | Fail | Fail | Fail | Fail | Fail |
| rank | Fail | Fail | Fail | Fail | Fail |
| remove-water | Fail | Fail | Fail | Fail | Fail |
| rms_velocity | Fail | Fail | Fail | Fail | Fail |
| rmse | Fail | Fail | Fail | Fail | Fail |
| rog | Fail | Fail | Fail | Fail | Fail |
| sasa | Fail | Fail | Fail | Fail | Fail |
| scaffold | Fail | Fail | Fail | Fail | Fail |
| seq-align | Fail | Fail | Fail | Fail | Fail |
| seq-trans | Fail | Fail | Fail | Fail | Fail |
| sequence | Fail | Fail | Fail | Fail | Fail |
| sle | Fail | Fail | Fail | Fail | Fail |
| spectral_r | Fail | Fail | Fail | Fail | Fail |
| find_peaks | Fail | Fail | Fail | Fail | Fail |
| speed_of_sound | Fail | Fail | Fail | Fail | Fail |
| substructure | Fail | Fail | Fail | Fail | Fail |
| tanimoto | Fail | Fail | Fail | Fail | Fail |
| unbdistance | Fail | Fail | Fail | Fail | Fail |
aa_polarity
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
[insert]
return countimport math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for x in sequence:
if x == 'N':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for x in sequence:
if x == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for x in sequence:
if x == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for char in sequence:
if char == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for char in sequence:
if char == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
adiabatic_expansion
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
[insert]
return T2
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + P1*math.exp(-gamma*T1)
T2 = T2 + P2*math.exp(-gamma*T2)
if __name__ == "__main__":
T1 = float(sys.argv[1])
P1 = float(sys.argv[2])
P2 = float(sys.argv[3])
gamma = float(sys.argv[4])
print cooling(T1,P1,P2,gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 17)
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + gamma*((P2-P1)/(T1-T2))
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
local variable 'T2' referenced before assignment
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + gamma*P1*P2*(math.exp((P2-P1)/T1))
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + gamma * (P2-P1)
300 else 300
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
unindent does not match any outer indentation level (<string>, line 10)
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + gamma * P1
T3 = T2 + gamma * P2
T4 = T3
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
alignment
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
[insert]
return trajimport mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj = traj.select([frame_index])
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
expected str, bytes or os.PathLike object, not Trajectory
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj = md.AlignTraj(traj, frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
expected str, bytes or os.PathLike object, not Trajectory
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj.select_atoms("resname *" + frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
expected str, bytes or os.PathLike object, not Trajectory
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj = md.AlignTraj(traj)
traj = md.AlignTraj(traj, frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
expected str, bytes or os.PathLike object, not Trajectory
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj.align(frame_index)
|/
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
invalid syntax (<string>, line 13)
angle
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
[insert]
return angleimport numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
aromatic_aa
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
[insert]
return countimport math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for x in sequence:
if x == 'A' or x == 'a':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for x in sequence:
if x == 'A':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for letter in sequence:
if letter == 'A':
count += 1
return count
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for x in sequence:
if x in "ACGT":
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for letter in sequence:
if letter == 'A':
count += 1
return count
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
arrhenius
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
[insert]
return k1import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = math.sqrt(T2/T1)
k2 = k1/(math.pow(T1,2)/math.pow(T2,2))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2/T1)**(k2/2)
k2 = k1/(math.sqrt(2*math.pi)*Ea)
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2/T1)*((T2/T1)**2 - Ea**2)
k2 = k1/(T2/T1)
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2/T1)**(k2/2)
k2 = k1/(math.exp((k2/2)/Ea))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2/T1)**(k2/2)
k2 = k1/(1+k1/Ea)
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
bimolecular
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
[insert]
return rateimport math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
|/
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = 0
for x in range(0,k):
rate += A*math.pow(B*math.pow(math.log(x/k),2),2)
if __name__ == "__main__":
print bimolecular_rate(2,1,2)
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 17)
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
|/
|/
|/
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 14)
bb_rad
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
[insert]
return Bimport numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T)/(lam**2 + T)
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T**2) / (lam**2 - T**2 - lam*T*T)
B = B * T
|/
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 12)
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T**2)/(lam**2 - T**2 - lam*T)
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T)/(lam**2 + T)
B = B**0.5
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T**2) / (lam**2 - T**2)
B = B * T
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
blast
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
[insert]
return e, idimport requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq).upper()
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq).upper()
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(',','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
bravais
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
[insert]
return nameimport math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
group_number = math.floor(group_number)
group_number = group_number - 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 8
group_number = group_number + 1
group_number = group_number % 16
group_number = group_number + 1
group_number = group_number % 32
group_number = group_number + 1
group_number = group_number % 64
group_number = group_number + 1
group_number = group_number % 128
group_number = group_number + 1
group_number = group_number % 256
group_number = group_number + 1
group_number = group_number % 512
group_number = group_number + 1
group_number = group_number % 1024
group_number = group_number + 1
group_number = group_number % 2048
group_number = group_number + 1
group_number = group_number % 4096
group_number = group_number + 1
group_number = group_number % 8192
group_number = group_number + 1
group_number = group_number % 16384
group_number = group_number + 1
group_number = group_number % 32768
group_number = group_number + 1
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
name 'name' is not defined
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
lattice = {
0: 'X',
1: 'Y',
2: 'Z',
3: 'A',
4: 'B',
5: 'C',
6: 'D',
7: 'E',
8: 'F',
9: 'G',
10: 'H',
11: 'I',
12: 'J',
13: 'K',
14: 'L',
15: 'M',
16: 'N',
17: 'O',
18: 'P',
19: 'Q',
20: 'R',
21: 'S',
22: 'T',
23: 'U',
24: 'V',
25: 'W',
26: 'X',
27: 'Y',
28: 'Z',
29: 'A',
30: 'B',
31: 'C',
32: 'D',
33: 'E',
34: 'F',
35: 'G',
36: 'H',
37: 'I',
38: 'J',
39: 'K',
40: 'L',
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 54)
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
if group_number 1:
raise ValueError("group_number must be greater than 0")
group_number = math.floor(group_number)
group_number = group_number - 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 11)
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
lattice = group_number - 1
lattice_letters = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
]
lattice_letters_reversed = [
letter[::-1] for letter in lattice_letters
]
lattice_letters_reversed.reverse()
lattice_letters_reversed = "".join(lattice_letters_reversed)
lattice_letters_reversed = lattice_letters_reversed.upper()
lattice_letters_reversed = lattice_letters_reversed.replace("_", "")
lattice_letters_reversed = lattice_letters_reversed.replace("L", "")
lattice_letters_reversed = lattice_letters_reversed.replace("M", "")
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
name 'name' is not defined
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
9:
raise ValueError("Invalid group number")
group_number = group_number - 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
unindent does not match any outer indentation level (<string>, line 11)
canonicalize
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
[insert]
return canon_listimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol))
return canonical_list
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_smiles = Chem.MolToSmiles(mol)
canon_list.append(canonical_smiles)
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol))
return canonical_list
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_smiles = Chem.MolToSmiles(mol, canonical=True)
canon_list.append(canonical_smiles)
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
canonical_smiles = Chem.MolToSmiles(mol, canonical=True)
canon_list.append(canonical_smiles)
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
carnot_efficiency
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
[insert]
return eps
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = T_hot / T_cold
1:
eps = eps
if eps 1:
eps = 1
return eps
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
unindent does not match any outer indentation level (<string>, line 10)
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = math.sqrt((T_hot / T_cold) ** 2 + (T_hot / T_cold) ** 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = math.pow(T_hot / T_cold, 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = T_hot / T_cold
eps = math.pow(eps, 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = math.sqrt((T_hot / T_cold) ** 2 + (T_hot / T_hot) ** 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
claussius
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
[insert]
return P2
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = HVap*T2/(T1+T2)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1/(HVap*T2)
P2 = P2*(T2-T1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 + (HVap - T1) * (T2 - T1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 + HVap * math.exp(-(T2 - T1)/T1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 + HVap * math.exp(-(T2 - T1)/T1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
compare_electronegativity
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
[insert]
return resultimport math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.Electronegativity(element1)
result = False
electronegativity:
result = True
else:
result = False
return result
if __name__ == "__main__":
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
unindent does not match any outer indentation level (<string>, line 12)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.electronegativity(element1,element2)
0.0
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
unindent does not match any outer indentation level (<string>, line 11)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.electronegativity(element1,element2)
mendeleev.electronegativity(element2,element1)
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
unindent does not match any outer indentation level (<string>, line 11)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.electronegativity(element1,element2)
0.0:
return True
else:
return False
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
unindent does not match any outer indentation level (<string>, line 11)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = mendeleev.compare(element1,element2)
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
module 'mendeleev' has no attribute 'compare'
condiff_1d
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
[insert]
return diffimport numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
cubes
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
[insert]
return simport math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(1, n+1):
s *= i
return s
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n * n * n
for i in range(1, n+1):
s *= i
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(1, int(math.sqrt(n))+1):
s += i
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(2, int(math.sqrt(n))+1):
s *= i
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(1, n+1):
s *= i
return s
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
de_broglie
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
[insert]
return limport math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l = m*math.pow(10,-(v/10))
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
|/
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 16)
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
|/
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
derivative1d-ch
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
[insert]
return dimport numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-c)*(x-a)/(a+b+c)
return dx
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-a)
dy=(c-x)
|/
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
invalid syntax (<string>, line 13)
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-c)*(x-a)
dy=(b-c)*(x-a)
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'd' is not defined
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-c)*(x-a)/(a+b)
dy=(b-c)*(x-c)/(a+b)
dz=(b-c)*(x-c)/(a+b)
|/
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
invalid syntax (<string>, line 14)
import numpy as np
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-a)/(c*x)
|/d
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
invalid syntax (<string>, line 14)
derivative_2deg
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
[insert]
return derivimport numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'y' is not defined
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'y' is not defined
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d([a,b,c])
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'y' is not defined
import numpy as np
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'y' is not defined
descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
[insert]
return descriptorsimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=3, nBits=2048))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
module 'rdkit.Chem.Descriptors' has no attribute 'MolDescriptors'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=3, nBits=2048))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
module 'rdkit.Chem.Descriptors' has no attribute 'MolDescriptors'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=4, useFeatures=False))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
dipole
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
[insert]
return dipole_momentimport numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
i', charges, coordinates)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
EOL while scanning string literal (<string>, line 11)
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(3):
dipole_moment[i] = np.power(coordinates[i,0] - charges[i,0], 2) + np.power(coordinates[i,1] - charges[i,1], 2) + np.power(coordinates[i,2] - charges[i,2], 2)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
too many indices for array: array is 1-dimensional, but 2 were indexed
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros((len(coordinates), 3))
for i in range(len(coordinates)):
dipole[i,0] = coordinates[i][0]
dipole[i,1] = coordinates[i][1]
dipole[i,2] = charges[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
unsupported operand type(s) for -: 'float' and 'function'
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
i', charges, coordinates)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
EOL while scanning string literal (<string>, line 11)
import numpy as np
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
i', charges, coordinates)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
EOL while scanning string literal (<string>, line 11)
dou
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
[insert]
return dimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
bonds = mol.GetBonds()
bonds = [b for b in bonds if b.GetBeginAtomIdx() == b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.SINGLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx() not in [b.GetEndAtomIdx(), b.GetBeginAtomIdx()+1]]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.DOUBLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx() not in [b.GetEndAtomIdx(), b.GetBeginAtomIdx()+1]]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.TRIPLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx() not in [b.GetEndAtomIdx(), b.GetBeginAtomIdx()+1]]
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
bonds = mol.GetBonds()
bonds = [b for b in bonds if b.GetBeginAtomIdx() == b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.SINGLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.DOUBLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.TRIPLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.AROMATIC]
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
bonds = mol.GetBonds()
bondCount = len(bonds)
bondHash = rdMolHash.MolHash(bonds)
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Python argument types in
rdkit.Chem.rdMolHash.MolHash(_ROBondSeq)
did not match C++ signature:
MolHash(RDKit::ROMol mol, RDKit::MolHash::HashFunction func)
eigen-ch
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/v
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 13)
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 13)
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/
|/
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 15)
import numpy as np
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/
|/
|/
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 15)
eigen
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
[insert]
return w,vimport numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
|/
|/
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 13)
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 25)
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
|/ file dstars=0
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
|/
|/
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 13)
element_mass
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
[insert]
return massimport math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.mass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev' has no attribute 'mass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.ElementMass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev' has no attribute 'ElementMass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.elements.get_mass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev.elements' has no attribute 'get_mass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.ElementMass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev' has no attribute 'ElementMass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.ElementMass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev' has no attribute 'ElementMass'
element_name
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
[insert]
return simport math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
invalid syntax (<string>, line 13)
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
invalid syntax (<string>, line 13)
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
module 'mendeleev' has no attribute 'symbol'
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
invalid syntax (<string>, line 13)
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
invalid syntax (<string>, line 13)
energy_of_e
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
[insert]
return energyimport math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 0.0
for i in range(1,n+1):
energy += i
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 1
for i in range(1, n+1):
energy *= i
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = n * (n + 1)
energy -= n * n * n * n * n
energy -= n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n * n * n * n * n * n * n * n
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 0.
for i in range(1, int(math.sqrt(n))+1):
energy += i * (i-1) * (i-2) * (i-3) * (i-4) * (i-5) * (i-6) * (i-7) * (i-8) * (i-9) * (i-10) * (i-11) * (i-12) * (i-13) * (i-14) * (i-15) * (i-16) * (i-17) * (i-18) * (i-19) * (i-20) * (i-21) * (i-22) * (i-23) * (i-24) * (i-25) * (i-26) * (i-27) * (i-28) * (i-29) * (i-30)
return energy
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 0.
for i in range(1, int(math.sqrt(n))+1):
energy += i * (n**i)
if __name__ == "__main__":
n = int(sys.argv[1])
energy = energy_of_e(n)
print(energy)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
'return' outside function (<string>, line 21)
find_indices
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
[insert]
return idximport mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.resname!= 'CA')[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.select('CA') == True)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.select('CA') == True)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.select('CA') == True)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
0)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
unindent does not match any outer indentation level (<string>, line 11)
force_constant
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
[insert]
return kimport numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k = k*wave_len
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k = k*wave_len
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k = k*wave_len
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2 # reduced mass
k = k*wave_len**2 # wave length in cm^-1 units
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/(m1+m2) * np.exp(-(wave_len/wave_len.value)**2)
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 13)
fourier_1d
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
[insert]
return wimport numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
|/ file dstars=0
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
|/ file dstars=0
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
invalid syntax (<string>, line 11)
freezing_depression
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
[insert]
return deltaTimport math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
KfK = Kf*Kf
deltaT = KfK/math.sqrt(m)
if __name__ == "__main__":
Kf = float(sys.argv[1])
m = float(sys.argv[2])
print freezing_depression(Kf,m)
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
invalid syntax (<string>, line 17)
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m/(Kf+m)
if deltaT 0:
deltaT = 0
else:
deltaT = math.floor(deltaT)
return deltaT
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
invalid syntax (<string>, line 12)
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
name 'deltaT' is not defined
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT=Kf*m
if deltaT0:
deltaT=0
return deltaT
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
name 'deltaT0' is not defined
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
KfK = Kf*Kf
deltaT = KfK*m
if deltaT 0:
deltaT = 0
else:
deltaT = deltaT/KfK
return deltaT
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
invalid syntax (<string>, line 13)
genpos
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
[insert]
return generatorsimport requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for i in range(1,11):
url = "http://www.crystallography.com/spacegroups/" + str(gnum) + "/general-positions.aspx"
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')
generators.append([])
for tr in rows:
cols = tr.find_all('td')
generators[i].append([])
for td in cols:
generators[i][-1].append(td.text)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
'NoneType' object has no attribute 'find_all'
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
base_url = "http://ec.europa.eu/eurostat/eurostat-data/"
page_num = 1
while page_num gnum:
page_url = base_url + str(page_num)
page_response = requests.get(page_url)
page_soup = BeautifulSoup(page_response.text, 'html.parser')
generators.append(page_soup.find_all('table', class_='table')[0])
page_num += 1
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
invalid syntax (<string>, line 16)
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for g in range(1, gnum+1):
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
expected an indented block (<string>, line 13)
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for g in range(1,11):
generators.append(g*gnum)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
Success
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
base_url = 'http://www.internationalcrystallography.com/crystallography/crystallography/'
soup = BeautifulSoup(requests.get(base_url+str(gnum)).text, 'html.parser')
table = soup.find('table', class_='table')
rows = table.find_all('tr')
for row in rows:
cols = row.find_all('td')
generators.append(cols[0].text)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
HTTPConnectionPool(host='www.internationalcrystallography.com', port=80): Max retries exceeded with url: /crystallography/crystallography/66 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f5520ef4880>: Failed to establish a new connection: [Errno -2] Name or service not known'))
heating_water
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
[insert]
return q
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = 0.0
for j in range(n):
q += (T1 * math.pow(T2, j))
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = 0.0
for j in range(n):
q += (T1 - T2) * (T1 - T2) / ((T1 - T2) * (T1 - T2))
T1 -= T2
T2 -= T2
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = ((T1-T2)/(n*(n-1))) * math.log(T2/T1)
if __name__ == "__main__":
n = int(sys.argv[1])
T1 = float(sys.argv[2])
T2 = float(sys.argv[3])
print heating_energy(n, T1, T2)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = (T1 * n) / (T2 * n)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
hydrophobic_res
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
[insert]
return residsimport mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = mdtraj.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'H':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
name 'mdtraj' is not defined
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = mdtraj.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
expected an indented block (<string>, line 14)
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = md.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'H':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Trajectory' object has no attribute 'models'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = md.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'HOH':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Trajectory' object has no attribute 'models'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = mdtraj.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'H':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
name 'mdtraj' is not defined
ideal_gas
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
[insert]
return Pimport math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*T*math.exp(-n/2)
P = P*1000
if __name__ == "__main__":
n = int(sys.argv[1])
V = float(sys.argv[2])
T = float(sys.argv[3])
P = ideal_gas_pressure(n,V,T)
print P
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Missing parentheses in call to 'print'. Did you mean print(P)? (<string>, line 18)
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*math.exp(-T/n)
return P
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*T/(n*math.pow(10,9))
|/ file dstars=0
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 13)
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*math.exp(-T/n)
return P
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*T*math.exp(-n*T/V)
return P
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
integral
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
[insert]
return integralimport numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
|/
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
invalid syntax (<string>, line 12)
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
|/
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
invalid syntax (<string>, line 12)
import numpy as np
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
|/
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
invalid syntax (<string>, line 12)
trap
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
[insert]
return integralimport numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * f(b) / i
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * np.exp(-(b - a) * i)
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * np.trapz(b - a, a)
return integral
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
diff requires input that is at least one dimensional
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * np.exp(-b * i)
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += a * (f(a) + f(b))
a, b = b, a + b
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
loop of ufunc does not support argument 0 of type int which has no callable sqrt method
invert_matrix
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
[insert]
return Ainvimport numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
|/
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
invalid syntax (<string>, line 12)
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
|/
|/ file dstars=0
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
invalid syntax (<string>, line 12)
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
|/
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
invalid syntax (<string>, line 12)
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
|/
|/ file dstars=1
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
invalid syntax (<string>, line 12)
import numpy as np
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
name 'Ainv' is not defined
iupac2smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
[insert]
return SMILESimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace('-','')
IUPAC = IUPAC.replace('_','')
IUPAC = IUPAC.replace('(','')
IUPAC = IUPAC.replace(')','')
IUPAC = IUPAC.replace(',','')
IUPAC = IUPAC.replace('.','')
IUPAC = IUPAC.replace(';','')
IUPAC = IUPAC.replace(':','')
IUPAC = IUPAC.replace('=','')
IUPAC = IUPAC.replace('!','')
IUPAC = IUPAC.replace('~','')
IUPAC = IUPAC.replace('@','')
IUPAC = IUPAC.replace('#','')
IUPAC = IUPAC.replace('$','')
IUPAC = IUPAC.replace('%','')
IUPAC = IUPAC.replace('^','')
IUPAC = IUPAC.replace('&','')
IUPAC = IUPAC.replace('*','')
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
name 'SMILES' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
SMILES = []
for char in IUPAC:
if char.isupper():
SMILES.append(char)
else:
SMILES.append(char.upper())
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace("-", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
name 'SMILES' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace("-", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
name 'SMILES' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace("-", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
name 'SMILES' is not defined
kld
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
[insert]
return lossimport numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0.0
for i in range(len(true_data)):
loss += (true_data.data[i]-predicted_data.data[i])**2
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
langevin_dynamics
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
[insert]
return x_traj, v_trajimport numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
F() takes from 1 to 2 positional arguments but 4 were given
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
F() takes from 1 to 2 positional arguments but 4 were given
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
F() takes from 1 to 2 positional arguments but 4 were given
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
F() takes from 1 to 2 positional arguments but 4 were given
import numpy as np
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
x_traj[-1] = x0
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
F() takes from 1 to 2 positional arguments but 4 were given
weighted-least-squares
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
[insert]
return betaimport numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.dot(x.T, np.dot(w, x))
|/
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 10)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
|/
|/
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 10)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.dot(x.T, np.dot(w, x))
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 10)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
|/
|/
|/
|/
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 10)
import numpy as np
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
|/
|/
|/
|/
|/
|/
|/
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 10)
lipinski_rule_of_five
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
[insert]
return resultimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
mape
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
[insert]
return eimport math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = y_hat - y
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = math.fabs(y_hat - y)
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = (y_hat-y)/y_hat
|/
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = y_hat - y
|/
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = y_hat - y
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 16)
mapping_operator
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
[insert]
return Mimport MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.n_atoms, molecule.n_atoms))
for i in range(molecule.n_atoms):
for j in range(molecule.n_atoms):
M[i][j] = beads_mappings[i][j]
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
invalid syntax (<string>, line 16)
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.n_atoms, molecule.n_atoms))
for bead, bead_mapping in beads_mappings.items():
atom_selection = bead_mapping['atom_selection']
atom_selection_atoms = bead_mapping['atom_selection_atoms']
atom_selection_masses = bead_mapping['atom_selection_masses']
atom_selection_masses = atom_selection_masses[atom_selection]
atom_selection_masses = atom_selection_masses[atom_selection_atoms]
atom_selection_masses = atom_selection_masses / np.sum(atom_selection_masses)
atom_selection_masses = atom_selection_masses * bead_mapping['atom_selection_weight']
atom_selection_masses = atom_selection_masses.sum(axis=0)
atom_selection_masses = atom_selection_masses / np.sum(atom_selection_masses)
atom_selection_masses = atom_selection_masses.reshape((molecule.n_atoms, molecule.n_atoms))
M[atom_selection, atom_selection] = atom_selection_masses
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'items'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), len(beads_mappings)))
for i in range(len(beads_mappings)):
for j in range(len(beads_mappings)):
M[i][j] = molecule.GetAtomWithIdx(beads_mappings[i]).GetAtomWithIdx(beads_mappings[j]).GetDegree()
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
invalid syntax (<string>, line 16)
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), len(beads_mappings)))
for i in range(len(beads_mappings)):
for j in range(len(beads_mappings)):
M[i][j] = molecule.GetAtomWithIdx(beads_mappings[i][j]).GetAtomWithIdx(beads_mappings[j][i]).GetDegree()
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
invalid syntax (<string>, line 16)
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(molecule), len(molecule)))
for i in range(len(molecule)):
for j in range(len(molecule)):
if beads_mappings[i][j] == 1:
M[i][j] = 1.0
else:
M[i][j] = 0.0
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
invalid syntax (<string>, line 19)
matpow
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
[insert]
return rimport numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.zeros_like(x)
r[:,0] = x[:,0]**n
r[:,1] = x[:,1]**n
r[:,2] = x[:,2]**n
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
index 2 is out of bounds for axis 1 with size 2
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.zeros_like(x)
r[:,0] = x[:,0]**n
r[:,1] = x[:,1]**n
r[:,2] = x[:,2]**n
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
index 2 is out of bounds for axis 1 with size 2
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
matrix_factorial
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
[insert]
return fimport numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
if n == 0:
return 1
else:
return n * matrix_factorial(n - 1)
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.empty([n,n])
for i in range(n):
for j in range(n):
f[i,j] = i**j
|/
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
invalid syntax (<string>, line 14)
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros((n, n))
for i in range(n):
for j in range(n):
f[i, j] = f[i, j] * i
f[j, i] = f[i, j]
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.matrix(np.zeros((n,n)))
for i in range(n):
for j in range(n):
f[i,j] = f[j,i]*i
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
if n == 1:
return 1
else:
return n * matrix_factorial(n - 1)
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
max-boltz
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
[insert]
return simport math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(T/M)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(T/M)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(M*T/1000)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(T*M/1000)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(M*T/1000)
|/s
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
michaelis
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
[insert]
return v
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax
for t in range(S-1):
v = v * math.exp(-t/Km)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * math.exp(-S/Km)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax/S
v:
v = Km
else:
v = Km
return v
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
unindent does not match any outer indentation level (<string>, line 10)
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S * math.exp(-Km * S)
if v 0.1:
v = 0.1
return v
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 10)
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S * Km
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
mol_charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
[insert]
return chargeimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
net_charge
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
[insert]
return chargeimport math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(abs(ord(c) - 65))
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
math domain error
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(c.count('N'))
|/
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
invalid syntax (<string>, line 18)
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += c
return charge
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
unsupported operand type(s) for +=: 'int' and 'str'
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(c.count('N'))
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
math domain error
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(abs(ord(c) - 97))
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
solve_ode
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
[insert]
return solimport numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = []
for t in t:
sol.append(fn(t,y0))
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
can't multiply sequence by non-int of type 'float'
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = []
for t in t:
sol.append(fn(t,y0))
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
can't multiply sequence by non-int of type 'float'
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = []
for t in t:
sol.append(fn(t,y0))
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
can't multiply sequence by non-int of type 'float'
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = []
for t in t:
sol.append(fn(t,y0))
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
can't multiply sequence by non-int of type 'float'
import numpy as np
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros(len(t))
sol[0] = y0
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
setting an array element with a sequence.
ohe
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
[insert]
return vimport numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
|/
|/v
|/
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
|/ file dstars=0
|/
|/
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
invalid syntax (<string>, line 12)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
operands could not be broadcast together with shapes (10,) (10,5)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
|/ file dstars=0
|/
|/
|/
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
invalid syntax (<string>, line 12)
import numpy as np
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
v[a] = 1
|/ file dstars=0
|/
|/
|/
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
invalid syntax (<string>, line 13)
osmotic_pressure
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
[insert]
return pimport math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = 0.025 # atm /mol
rho = 1.225 # atm /mol
rho_l = 1.225 # atm /mol
rho_h = 1.225 # atm /mol
rho_l = rho_l*math.pow(T,2)
rho_h = rho_h*math.pow(T,2)
rho_l = rho_l*math.pow(T,3)
rho_h = rho_h*math.pow(T,3)
rho_l = rho_l*math.pow(T,4)
rho_h = rho_h*math.pow(T,4)
rho_l = rho_l*math.pow(T,5)
rho_h = rho_h*math.pow(T,5)
rho_l = rho_l*math.pow(T,6)
rho_h = rho_h*math.pow(T,6)
rho_l = rho_l*math.pow(T,7)
rho_h = rho_h*math.pow(T,7)
rho_l = rho_l*math.pow(T,8)
rho_h = rho_h*math.pow(T,8)
rho_l = rho_l*math.pow(T,9)
rho_h = rho_h*math.pow(T,9)
rho_l = rho_l*math.pow(T,10)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R * math.pow(T,3.0/4.0)
p = p * math.pow(Pi,3.0/4.0)
|/
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
invalid syntax (<string>, line 18)
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R * math.pow(T,3.0/3.0)
p = p * math.pow(Pi,3.0/3.0)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R*math.pow(T,3.0/4.0)
|/
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
invalid syntax (<string>, line 17)
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R*math.pow(T,3.0/4.0)
p = p/math.pi
|/
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
invalid syntax (<string>, line 18)
pair_wise
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
[insert]
return distancesimport mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(str(pdb_file))
alpha_carbons = pdb.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.unique()
alpha_carbons_length = len(alpha_carbons)
distances = np.zeros((alpha_carbons_length, alpha_carbons_length))
for i in range(alpha_carbons_length):
for j in range(alpha_carbons_length):
distances[i][j] = pdb.distances[i][j]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(str(pdb_file))
alpha_carbons = pdb.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.unique()
alpha_carbons = list(alpha_carbons)
alpha_carbons.sort()
distances = np.zeros((len(alpha_carbons), len(alpha_carbons)))
for i in range(len(alpha_carbons)):
for j in range(i+1, len(alpha_carbons)):
distances[i][j] = np.linalg.norm(pdb.select('name *[name!= "Carbon"]')[alpha_carbons[i]:alpha_carbons[j]])
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(str(pdb_file))
alpha_carbons = pdb.select('name CA')
alpha_carbons = alpha_carbons.sort('CA')
alpha_carbons = alpha_carbons.unique()
alpha_carbons = list(alpha_carbons)
alpha_carbons.sort()
distances = np.zeros((len(alpha_carbons), len(alpha_carbons)))
for i in range(len(alpha_carbons)):
for j in range(len(alpha_carbons)):
if i == j:
continue
distances[i][j] = alpha_carbons[i].distance(alpha_carbons[j])
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = mdtraj.load(pdb_file)
alpha_carbons = pdb.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(pdb_file)
alpha_carbons = pdb.select('name *[name ~ "*"]')
alpha_carbons = alpha_carbons.unique()
alpha_carbons_length = len(alpha_carbons)
distances = np.zeros(alpha_carbons_length)
for i in range(alpha_carbons_length):
alpha_carbon = alpha_carbons[i]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
pi
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
[insert]
return pi_estimport numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = 1.
for i in range(nsamples):
pi_est *= (2.*np.pi)
pi_est *= np.random.uniform()
return pi_est
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = np.pi
for i in range(nsamples):
pi_est = pi_est * 2
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = np.pi
pi_est *= nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = np.pi
pi_est *= nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = np.pi
for i in range(nsamples):
pi_est *= 2
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
pib_1d
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
[insert]
return eimport math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n*(m*L**2-L**2+hbar*hbar)
|/
|/
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n-m
for i in range(n+1):
e=e*math.exp(-0.5*hbar*L*i)
|/ file dstars=0
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=math.exp(-0.5*(n*m)/L)*hbar
|/
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n*(L**2-m*hbar)
|/
|/
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n-m
if eL: return 0
L: return -hbar
if e==L: return hbar
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 11)
pred_interval
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
[insert]
return nimport numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = len(p)
for i in range(n):
if p[i] pred_level:
return i
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
invalid syntax (<string>, line 10)
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = int(np.ceil(np.log(p)/np.log(pred_level)))
|/
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = len(p)
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
if n == 3:
return 3
if n == 4:
return 4
if n == 5:
return 5
if n == 6:
return 6
if n == 7:
return 7
if n == 8:
return 8
if n == 9:
return 9
if n == 10:
return 10
|/
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
invalid syntax (<string>, line 33)
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = int(np.floor(np.log(p)/np.log(pred_level)))
|/
|/ file dstars=0
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = len(p)
for i in range(n):
= pred_level:
return i
|/
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
expected an indented block (<string>, line 10)
pubchem
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
[insert]
return molsimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'http://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/similarity?query={}&format=smiles'.format(smiles)
response = requests.get(url)
smiles = response.text
mols = Chem.MolFromSmiles(smiles)
mols = Chem.AddHs(mols)
mols = Chem.MolToSmiles(mols, canonical=True)
mols = Chem.MolFromSmarts(mols)
mols = Chem.RemoveHs(mols)
mols = Chem.RemoveAtoms(mols, rdMolHash.HashesToAtomMap)
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(0))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(3))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(6))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(7))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(8))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(9))
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Python argument types in
rdkit.Chem.rdmolops.AddHs(NoneType)
did not match C++ signature:
AddHs(RDKit::ROMol mol, bool explicitOnly=False, bool addCoords=False, boost::python::api::object onlyOnAtoms=None, bool addResidueInfo=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/search?query={}&format=smiles'.format(smiles)
response = requests.get(url)
mol = Chem.MolFromSmiles(response.text)
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
mols = Chem.MolFromSmiles(smiles)
mols = [Chem.MolToSmiles(mol) for mol in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
'Mol' object is not iterable
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/search?query={}&format=sdf'.format(smiles)
response = requests.get(url)
data = response.json()
mols = []
for item in data['results']:
mols.append(Chem.MolFromSmiles(item['smiles'])) # Convert SMILES to Mol
mols = rdMolDescriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mols, 2)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Expecting value: line 1 column 1 (char 0)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'http://rest.pubchem.net/api/similarity?smiles=' + smiles
response = requests.get(url)
data = response.json()
mols = data['results']
mols = [Chem.MolFromSmiles(smi) for smi in mols]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
HTTPConnectionPool(host='rest.pubchem.net', port=80): Max retries exceeded with url: /api/similarity?smiles=CC=C=C(C(=O)N) (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f551c230df0>: Failed to establish a new connection: [Errno -2] Name or service not known'))
pyscf_energy
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
[insert]
return ground_energyimport pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [['H', (0., 0. , 0.)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
invalid syntax (<string>, line 29)
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.verbose = 0
mol.output = None
mol.atom = [['H', (0., 0. , 0.)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
invalid syntax (<string>, line 28)
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.kernel()
ground_energy = mol.energy_nuc()
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
qed
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
[insert]
return resultimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
quantile
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
[insert]
return resultimport numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
q] = np.nan
|/|/
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
unindent does not match any outer indentation level (<string>, line 9)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.percentile(a, q)
|/|/|/
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
invalid syntax (<string>, line 13)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
q))]
|/|/
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
unmatched ')' (<string>, line 9)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
result[np.where(a=q)] = a[np.where(a=q)]
q)]
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
unmatched ')' (<string>, line 10)
import numpy as np
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
result[np.where(a=q)] = a[np.where(a=q)]
q)]
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
unmatched ')' (<string>, line 10)
random_walk
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
[insert]
return trajimport numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.randn()
traj.append([x0, x1])
x0 = x1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.random()
traj.append([x0, x1])
x0 = x1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
traj.append(x0)
x0 = x0 + a
|/ file dstars=1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
invalid syntax (<string>, line 16)
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
traj.append([x0])
x0 += a
|/
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
invalid syntax (<string>, line 18)
import numpy as np
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.randn(1)
traj.append([x0, x1])
x0 = x1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Timeout
rank
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
[insert]
return rimport numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U,S,V = np.linalg.svd(M)
r = np.sum(np.diag(S))
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.argsort(s)
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
0)[0]
|/
|/
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
unindent does not match any outer indentation level (<string>, line 9)
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
rank = s.argmax()
|/
|/
|/
|/
|/
|/
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U,S,V = np.linalg.svd(M)
r = np.argsort(np.abs(S))
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
invalid syntax (<string>, line 14)
remove-water
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
[insert]
return new_trajimport mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file)
traj.top = traj.top.remove_solvent_from_topology(top_file)
new_traj = md.load(traj)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file)
top = md.load(top_file)
new_traj = traj.remove_solvent_from_topology(top)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file)
top = md.load(top_file)
new_traj = traj.remove_solvent_from_topology(top)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
new_traj = md.load(traj_file)
new_traj.top = md.load(top_file)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
new_traj = md.load(traj_file)
new_traj.top = md.load(top_file)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
rms_velocity
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
[insert]
return v_rms
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/3.0)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/3.0)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/T)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/(T*T))
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/T)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
rmse
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
[insert]
return eimport numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.power(a-b,2)
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2).mean()
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2).mean()
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2).mean()
|/
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2)
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
invalid syntax (<string>, line 11)
rog
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
[insert]
return rgimport mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = md.compute_radius_of_gyration(pdb)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
module 'mdtraj' has no attribute 'compute_radius_of_gyration'
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = protein_radius(pdb)
return rg
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
name 'protein_radius' is not defined
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = mdtraj.distances.compute_radius_of_gyration(pdb)
|/
|/
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
invalid syntax (<string>, line 17)
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = protein_radius(pdb)
return rg
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
name 'protein_radius' is not defined
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = protein_radius_of_gyration_from_pdb(pdb)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
name 'protein_radius_of_gyration_from_pdb' is not defined
sasa
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
[insert]
return sasaimport mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('CA')
sasa = sasa.sum(axis=1).reshape(pdb.n_atoms, 1)
|/
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
invalid syntax (<string>, line 16)
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('resname CA')
sasa.rename("CA")
|/
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
invalid syntax (<string>, line 16)
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = mdtraj.load(pdb_file)
sasa = pdb.select("resname like 'SASA%'")
sasa.compute_volume()
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
name 'mdtraj' is not defined
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('CA')
sasa = sasa.sum(axis=1).reshape(pdb.n_atoms, 1)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
'Trajectory' object has no attribute 'select'
scaffold
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
[insert]
return scaffold_smilesimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Chem.MolToSmiles(mol)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
seq-align
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
[insert]
return alignedfrom Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([seq1, seq2], gap_char="-")
aln.set_flags(aln.get_flags() | Align.DONT_OVERLAP)
aln.set_score_mode(Align.SCORE_ABSOLUTE)
aln.set_evalue(0.0)
aln.set_evalue_threshold(0.0)
aln.set_score_file("blast.out")
aln.set_evalue_cutoff(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
__init__() got an unexpected keyword argument 'gap_char'
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([seq1, seq2], gap_open='-', gap_extend='-')
return aln.get_alignment_string()
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
__init__() got an unexpected keyword argument 'gap_open'
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([SeqIO.to_dict(SeqRecord(Seq(seq1), "fasta")), SeqIO.to_dict(SeqRecord(Seq(seq2), "fasta"))])
aln.set_flags(AlignInfo.SMART_AA_NAMES)
aln.set_flags(AlignInfo.SMART_aa)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
name 'SeqRecord' is not defined
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = AlignIO.read(seq1, 'fasta')
aln = AlignIO.read(seq2, 'fasta')
aln = AlignIO.read(aln, 'blast')
aln = AlignIO.read(aln, 'blastp')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
name 'AlignIO' is not defined
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([seq1, seq2], gap_char="-")
aln.set_flags(aln.get_flags() | Align.AUTO_SEQUENCE)
aln.set_score_mode(aln.get_score_mode() | Align.SCORE_ALIGNMENT_SCORE)
aln.set_evalue(0)
aln.set_score_func(aln.get_score_func() | Align.SCORE_ALIGNMENT_SCORE)
aln.set_evalue_threshold(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
__init__() got an unexpected keyword argument 'gap_char'
seq-trans
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
[insert]
return prot_seqfrom Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
sequence
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
[insert]
return ximport numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.arange(s,e,l)
|/
|/ file dstars=0
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
s=np.float(s)
e=np.float(e)
l=np.float(l)
x=np.arange(s,e,l)
|/
|/
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
invalid syntax (<string>, line 18)
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
name 'x' is not defined
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.arange(s,e,l)
|/
|/|/
|/
|/
|/
|/
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
name 'x' is not defined
sle
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
[insert]
return ximport sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
x = sympy.symbols('x')
eqns = eqns.subs([('a_0x_0', 'c0'), ('a_1x_0', 'c1')])
eqns = eqns.subs([('b_0x_1', 'c0'), ('b_1x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
x = sympy.symbols('x')
eqns = eqns.subs({x:sympy.symbols('a_0x_0 + b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 + b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('a_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('a_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_0 = c0')})
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
x = sympy.symbols('x')
eqns = eqns.subs({x:sympy.symbols('a_0x_0 + b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 + b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('c_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('c_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('c_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('c_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('c_0x_0 = c0')})
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
a = eqns[0]
b = eqns[1]
c = eqns[2]
d = eqns[3]
e = eqns[4]
f = eqns[5]
g = eqns[6]
h = eqns[7]
i = eqns[8]
j = eqns[9]
k = eqns[10]
l = eqns[11]
m = eqns[12]
n = eqns[13]
o = eqns[14]
p = eqns[15]
q = eqns[16]
r = eqns[17]
s = eqns[18]
t = eqns[19]
u = eqns[20]
v = eqns[21]
w = eqns[22]
x = sympy.Matrix([[a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p],[q,r,s,t,u,v,w,x,y,z,w]])
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
x = sympy.symbols('x')
eqns = eqns.subs({x:sympy.symbols('a_0x_0 + b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 + b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('a_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('a_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_1 = c1')})
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
spectral_r
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
[insert]
return sradiusimport numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2,axis=1)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2, axis=1)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2, axis=1)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2)
|/
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
invalid syntax (<string>, line 11)
import numpy as np
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2)
|/
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
invalid syntax (<string>, line 11)
find_peaks
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
[insert]
return wavenumbersimport numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
wavenumbers = []
for peak in peaks:
wavenumbers.append(peak[0])
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peak_positions, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
peak_positions = np.asarray(peak_positions)
peak_positions.sort()
peak_positions = peak_positions[::-1]
peak_positions = peak_positions[:npeaks]
return peak_positions
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
peaks = np.asarray(peaks)
peaks.sort()
peaks = peaks[:npeaks]
return peaks
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
peaks = peaks[::-1]
peaks = [peaks[i] for i in xrange(len(peaks))]
return peaks
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
wavenumbers = []
for p in peaks:
wavenumbers.append(p[0])
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
speed_of_sound
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
[insert]
return s
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = m * gamma * T
if __name__ == "__main__":
T = int(sys.argv[1])
m = float(sys.argv[2])
gamma = float(sys.argv[3])
print speed_of_sound(T,m,gamma)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 16)
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = m*T*math.exp(-gamma*T)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = T*m*math.exp(-gamma*T)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = T*m*gamma
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = T*m*gamma
s = math.floor(s)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
substructure
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
[insert]
return idximport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.RemoveHs(mol_list)
mol_list = Chem.RemoveAtoms(mol_list, 1)
mol_list = Chem.RemoveAtoms(mol_list, 2)
mol_list = Chem.RemoveAtoms(mol_list, 3)
mol_list = Chem.RemoveAtoms(mol_list, 4)
mol_list = Chem.RemoveAtoms(mol_list, 5)
mol_list = Chem.RemoveAtoms(mol_list, 6)
mol_list = Chem.RemoveAtoms(mol_list, 7)
mol_list = Chem.RemoveAtoms(mol_list, 8)
mol_list = Chem.RemoveAtoms(mol_list, 9)
mol_list = Chem.RemoveAtoms(mol_list, 10)
mol_list = Chem.RemoveAtoms(mol_list, 11)
mol_list = Chem.RemoveAtoms(mol_list, 12)
mol_list = Chem.RemoveAtoms(mol_list, 13)
mol_list = Chem.RemoveAtoms(mol_list, 14)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = [Chem.MolFromSmiles(smiles) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.RemoveHs(mol_list)
mol_list = Chem.RemoveAtoms(mol_list, 1)
mol_list = Chem.RemoveAtoms(mol_list, 2)
mol_list = Chem.RemoveAtoms(mol_list, 3)
mol_list = Chem.RemoveAtoms(mol_list, 4)
mol_list = Chem.RemoveAtoms(mol_list, 5)
mol_list = Chem.RemoveAtoms(mol_list, 6)
mol_list = Chem.RemoveAtoms(mol_list, 7)
mol_list = Chem.RemoveAtoms(mol_list, 8)
mol_list = Chem.RemoveAtoms(mol_list, 9)
mol_list = Chem.RemoveAtoms(mol_list, 10)
mol_list = Chem.RemoveAtoms(mol_list, 11)
mol_list = Chem.RemoveAtoms(mol_list, 12)
mol_list = Chem.RemoveAtoms(mol_list, 13)
mol_list = Chem.RemoveAtoms(mol_list, 14)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = [Chem.MolFromSmiles(smiles) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
tanimoto
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
[insert]
return simport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("NumBits", bits)
scaffold.SetProp("NumAtomPairs", len(smiles_list))
scaffold.SetProp("NumExplicitHs", 0)
scaffold.SetProp("NumImplicitHs", 0)
scaffold.SetProp("NumRotatableBonds", 0)
scaffold.SetProp("NumPeriodicBonds", 0)
scaffold.SetProp("NumBonds", 0)
scaffold.SetProp("NumBondBonds", 0)
scaffold.SetProp("NumHs", 0)
scaffold.SetProp("NumHsAtomPairs", 0)
scaffold.SetProp("NumHsBonds", 0)
scaffold.SetProp("NumHsBondBonds", 0)
scaffold.SetProp("NumHsBondBondBonds", 0)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("NumBits", bits)
scaffold.SetProp("MurckoPhi", True)
scaffold.SetProp("MurckoPhiBits", bits)
scaffold.SetProp("MurckoPhiPrecision", bits)
scaffold.SetProp("MurckoPhiMinBits", bits)
scaffold.SetProp("MurckoPhiMaxBits", bits)
scaffold.SetProp("MurckoPhiSeed", 0)
scaffold.SetProp("MurckoPhiSeedBits", bits)
scaffold.SetProp("MurckoPhiSeedPrecision", bits)
scaffold.SetProp("MurckoPhiSeedMinBits", bits)
scaffold.SetProp("MurckoPhiSeedMaxBits", bits)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.SetProp("GenerateMurckoFlag", 0)
scaffold.SetProp("MurckoBits", bits)
scaffold.SetProp("MurckoPhi", 3)
scaffold.SetProp("MurckoMinVal", 0)
scaffold.SetProp("MurckoSeed", 0)
scaffold.SetProp("MurckoSeed2", 0)
scaffold.SetProp("MurckoSeed3", 0)
scaffold.SetProp("MurckoSeed4", 0)
scaffold.SetProp("MurckoSeed5", 0)
scaffold.SetProp("MurckoSeed6", 0)
scaffold.SetProp("MurckoSeed7", 0)
scaffold.SetProp("MurckoSeed8", 0)
scaffold.SetProp("MurckoSeed9", 0)
scaffold.SetProp("MurckoSeed10", 0)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("MurckoScaffoldParams.NumBits", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsError", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsWarning", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracy", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyError", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyWarning", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyAccuracy", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyAccuracyError", bits)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("MurckoScaffoldParams.NumBits", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsFingerprint", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAtom", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsBond", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAngle", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsBondAngle", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsHBond", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsHAngle", bits)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
unbdistance
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
[insert]
return resultimport mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_resid=md.resids[lig_str]
lig_traj = md.load(traj,top=lig_resid).get_frame(0)
lig_traj = lig_traj[lig_traj.select('resname '+lig_str)]
lig_traj = lig_traj[lig_traj.select('name '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_resid=lig_str.split("_")
lig_resid=lig_resid[0]
lig_resid=lig_resid[1:]
lig_resid=lig_resid.split(":")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("-")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("(")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split(")")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("+")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("-")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("*")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("=")
lig_resid=lig_resid[0]
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_atoms = traj.resids[lig_str]
lig_atoms_center = lig_atoms.center()
lig_atoms_center = np.array(lig_atoms_center)
lig_atoms_center = lig_atoms_center.reshape((1,3))
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_str = lig_str.upper()
lig_atoms = md.get_atoms(traj,resname=lig_str)
lig_atoms = lig_atoms.reshape((-1,3))
lig_atoms[:,0] += traj[0].xyz[0]
lig_atoms[:,1] += traj[0].xyz[1]
lig_atoms[:,2] += traj[0].xyz[2]
lig_atoms[:,0] /= len(traj)
lig_atoms[:,1] /= len(traj)
lig_atoms[:,2] /= len(traj)
lig_atoms[:,0] -= traj[0].xyz[0]
lig_atoms[:,1] -= traj[0].xyz[1]
lig_atoms[:,2] -= traj[0].xyz[2]
lig_atoms[:,0] /= len(traj)
lig_atoms[:,1] /= len(traj)
lig_atoms[:,2] /= len(traj)
lig_atoms[:,0] -= traj[0].xyz[0]
lig_atoms[:,1] -= traj[0].xyz[1]
lig_atoms[:,2] -= traj[0].xyz[2]
lig_atoms[:,0] /= len(traj)
lig_atoms[:,1] /= len(traj)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_traj = md.load(lig_str)
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'